0

I want to compare between two nested orderedDict dict, where i have to compare each and every key of dict1 Vs dict2.

>>> dict1 = OrderedDict([('a', OrderedDict([('b', '20'),
        ('c', '30'),('d', OrderedDict([('e', '40')]))]))])
>>> dict2 = OrderedDict([('a', OrderedDict([('b', '20'),
        ('c', '30'),('d', OrderedDict([('e', '50')]))]))])
for k,v in dict1.iteritems():
    for k1,v1 in v.iteritems():
        print "key %s, value  %s" %(k1,v1)
        for k2,v2 in dict2.iteritems():
            for k3,v3 in v2.iteritems():
               print "key %s, value  %s" %(k3,v3)

Output:


key b, value  20
key b, value  20
key c, value  30
key d, value  OrderedDict([('e', '50')])
key c, value  30
key b, value  20
key c, value  30
key d, value  OrderedDict([('e', '50')])
key d, value  OrderedDict([('e', '40')])
key b, value  20
key c, value  30
key d, value  OrderedDict([('e', '50')])

As the code is quite long, please help in writting in sort with comparision between (k1,v1) vs (k3,v3)

STripathy
  • 59
  • 1
  • 8
  • I'm not able to follow. Are you comparing whole dictionaries or just certain keys? – kokeen Aug 17 '19 at 05:53
  • @kokeen I want to compare each "key" & "value" of dict 1 with "key and "value" of dict 2.Since its nested ordereddict , so finding difficult to compare – STripathy Aug 17 '19 at 05:57
  • 2
    That's essentially comparing two whole dictionaries. [This](https://stackoverflow.com/questions/27265939/comparing-python-dictionaries-and-nested-dictionaries) might be a good start. – kokeen Aug 17 '19 at 06:00
  • In my case, i have to iterate through and compare between(k1,v1) and (k3,v3) , as my output shown. – STripathy Aug 17 '19 at 06:07
  • Check the link I've added in my previous comment. It helps in comparing nested dictionaries. – kokeen Aug 17 '19 at 06:09

1 Answers1

2

Data:

dict1 = OrderedDict([('a',
              OrderedDict([('b', '20'),
                           ('c', '30'),
                           ('d', OrderedDict([('e', '40')]))]))])

dict2 = OrderedDict([('a',
              OrderedDict([('b', '20'),
                           ('c', '30'),
                           ('d', OrderedDict([('e', '50')]))]))])

Perhaps unpacking the OrderedDicts into a DataFrame is a better option:

import pandas as pd
from pandas.io.json import json_normalize

dict_list = [dict1, dict2]  # more OrderedDicts can be added

df = pd.concat([json_normalize(x) for x in dict_list], sort=True).reset_index(drop=True)

df =

enter image description here

Also works if the keys are different:

enter image description here

print the product of df rows:

from itertools import product

dict_product = [list(product(df.iloc[y-1], df.iloc[y])) for y in df.index if y != 0]

print(dict_product)

[[('20', '20'),
  ('20', '30'),
  ('20', '50'),
  ('30', '20'),
  ('30', '30'),
  ('30', '50'),
  ('40', '20'),
  ('40', '30'),
  ('40', '50')]]
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158