[英]How to compare and merge two nested dictionaries into another nested dictionary of lists?
[英]How to compare nested dictionaries?
我有兩個嵌套的字典。
dict1 = {(t1,name):{('11','22'):{'33':'456','77':'891'},
('121','212'):{'32':'123', '23':'546'}}}
dict2 = {(t1,name):{('11','22'):{'33':'456','77':'891'},
('121','212'):{'32':'123', '23':'546'}}}
基本上,兩個命令是相同的。 但是我需要比較dict1
每個鍵,看看該鍵是否在dict2
存在(如果存在,則對應的值應與dict1
值匹配)。
這是我寫的。 但是無法得到最終結果。
for i,j in dict1.items():
# values of t1,name (i.e. inner key/value pairs of (t1,name)) might interchange
# order at times that is the reason I used sorted
for k,v in sorted(j.items()):
print k # prints - >('11',22')
print v # prints - > '33':'456','77':'891'
if i in dict2.keys():
# Here I need to make sure for outer key (t1,name), inner key/value pair of
# dict2 is same as inner key/value pair of dict1
對此冗長的解釋表示歉意。 我不確定我是否能夠清楚地解釋它。
不確定我了解您在尋找什么,但是您可以使用dict理解來構造所有匹配項:
>>> {k: v for k, v in dict1.items() if dict2[k] == v}
{('t1', 'name'): {('11', '22'): {'33': '456', '77': '891'},
('121', '212'): {'23': '546', '32': '123'}}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.