在一个字典中附加一个键并将嵌套的dict作为其值的字典列表

2024-09-29 22:04:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模式,我有一个嵌套字段列表,应该在其中。 基本上,我得到的是:

[{'name': 'a', 'type': 'string'}, 
{'name': 'b', 'type': 'string'}, 
{'name': 'c', 'type': 'string'}, 
{'name': 'd', 'type': 'string'}, 
{'name': 'e', 'type': 'string'}, 
{'name': 'attr', 'type': 'string'}, 
{'name': 'f', 'type': 'string'},
{'name': 'g', 'type': 'string'}, 
{'name': 'h', 'type': 'string'}, 
{'name': 'i', 'type': 'string'}, 
{'name': 'j', 'type': 'string'}, 
{'name': 'k', 'type': 'string'}]

但是当“name”是“attr”时,我想向它添加另一个dictionary k-v对,键是“fields”,值是另一个嵌套的dictionary列表,格式与上面的相同。这将使它看起来像:

[{'name': 'a', 'type': 'string'}, 
{'name': 'b', 'type': 'string'}, 
{'name': 'c', 'type': 'string'}, 
{'name': 'd', 'type': 'string'}, 
{'name': 'e', 'type': 'string'}, 
{'name': 'attr', 'type': 'string', 'fields': [{'name': 'aa',....}], 
{'name': 'f', 'type': 'string'},
{'name': 'g', 'type': 'string'}, 
{'name': 'h', 'type': 'string'}, 
{'name': 'i', 'type': 'string'}, 
{'name': 'j', 'type': 'string'}, 
{'name': 'k', 'type': 'string'}]

下面,主模式集和嵌套模式集都是我转换的集。你知道吗

finalschema = [{'name':l} for l in master_schema_set]
finalschemanested = [{'name':l} for l in nestedschemaset]

for i in finalschema:
    i.update({"type":'string'}) #all types will always be string
    for item,val in i.items():
        if val == 'attr':
            i.update({'fields':finalschemanested})

运行它会给我一个错误“dictionary changed size during iteration”,但最终这就是我想要的。实现这一目标的更好方法是什么?你知道吗


Tags: nameinfields列表forstringdictionary格式
3条回答

迭代Dict并切换到相同的Dict不是一个好主意。参考:Christoph Zwerschke's blog.

你需要改变你的代码,摆脱这种模式。对于列表和其他数据结构也是如此。在python2中,它从来不会以错误或警告的形式出现,循环会无休止地运行。 参考我的答案Raja Sakthiyan

在禁止迭代其键/值对时修改i,解决方法是只迭代他的键,并更新i,如下所示:

for i in finalschema:
    i.update({"type":'string'})
    for val in i.keys():
        if i[val] == 'attr':
            i['fields'] = finalschemanested

然而,这是在迭代时修改dict,这不是一个好主意。如果有更好的方法来做你想做的事情,你最好考虑一下重构。你知道吗

在您的例子中,您根本不需要迭代i,并将代码更改为以下内容:

for i in finalschema:
    i["type"] = 'string'
    if i['name'] == 'attr':
        i['fields'] = finalschemanested

另一方面,您使代码容易陷入python困境:i.update({'fields': finalschemanested})将在您要更新的每个dict中放置相同的finalschemanested对象。如果您多次执行此操作,则在两个不同的位置有相同的对象,这意味着修改一个位置将导致(可能不需要的)修改另一个位置。考虑使用copy模块:

from copy import deepcopy
... 
       i.update({'fields': deepcopy(finalschemanested)})
...

尝试:

for i in finalschema:
    i.update({"type":'string'}) #all types will always be string
    if i['name'] == 'attr':
        i.update({'fields':finalschemanested})
  • 注意:由于错误状态,在迭代对象时不要尝试更新dict。你知道吗

相关问题 更多 >

    热门问题