如何比较嵌套字典?

时间:2017-06-07 01:59:32

标签: python nested

我有两个嵌套的词典。

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

对这个冗长的解释道歉。我不确定我是否能够清楚地解释它。

1 个答案:

答案 0 :(得分:1)

不确定我理解你在寻找什么,但你可以使用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'}}}