![](/img/trans.png)
[英]How to check if dictionary is within a list of dictionaries on both key and value of dict, where dicts can be nested?
[英]Appending list of dictionaries with an additional key in one dictionary and a nested dict as its value
我有一個模式,並且有一個嵌套字段的列表,應該在其中。 基本上,我有:
[{'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'}]
但是,當“名稱”為“ attr”時,我想向其添加另一個字典kv對,其鍵為“字段”,值作為另一個嵌套的字典列表,格式與上述格式相同。 這將使其看起來像:
[{'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'}]
在下面,master_schema_set和nestedschemaset都是我轉換的集。
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})
運行此命令會給我一個錯誤“字典在迭代過程中更改了大小”,但最終這就是我想要的。 有什么更好的方法來實現這一目標?
嘗試:
for i in finalschema:
i.update({"type":'string'}) #all types will always be string
if i['name'] == 'attr':
i.update({'fields':finalschemanested})
禁止在迭代其鍵/值對時修改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})
: i.update({'fields': finalschemanested})
會將相同的finalschemanested
對象放入要更新的每個字典中。 如果您多次執行此操作,則在兩個不同的位置擁有相同的對象,這意味着修改一個位置會導致在另一個位置進行(可能是不需要的)修改。 考慮使用copy
模塊:
from copy import deepcopy
...
i.update({'fields': deepcopy(finalschemanested)})
...
迭代Dict
並切換到同一Dict
不是一個好主意。 參見: Christoph Zwerschke的博客。
您需要通過這種模式來更改代碼。 列表和其他數據結構都是如此。 在python2中,它永遠不會顯示為錯誤或警告,並且循環不斷。 請參閱我的答案之一Raja Sakthiyan
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.