1

I have two 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'}}}

Basically both the dicts are same. But I need to compare each key in dict1 and see if that key exists in dict2 (if exists the corresponding value should be matched with dict1 value).

Here is what I have written. But couldn't get the end result.

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

Apologies for this lengthy explanation. I'm not sure whether I am able to explain it clearly.

sophros
  • 14,672
  • 11
  • 46
  • 75
Krishna Chaitanya
  • 181
  • 2
  • 3
  • 10
  • What should the end result be, `True` or `False`? Where should it be stored? – martineau Jun 07 '17 at 02:09
  • Possible duplicate of [Comparing Python dictionaries and nested dictionaries](https://stackoverflow.com/questions/27265939/comparing-python-dictionaries-and-nested-dictionaries) – sophros Oct 23 '19 at 14:01

1 Answers1

1

Not sure I understand what you are looking for but you can use a dict comprehension to construct all the matches:

>>> {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'}}}
AChampion
  • 29,683
  • 4
  • 59
  • 75