Python 如何比较嵌套字典?
我有两本嵌套字典Python 如何比较嵌套字典?,python,dictionary,nested,comparison,Python,Dictionary,Nested,Comparison,我有两本嵌套字典 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 = {(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'}}}
最终结果应该是什么,
True
还是False
?它应该存储在哪里?如果我有一个字典列表来比较公共键值,那么如何使用它。。?