Home > Enterprise >  Separate unique and common nested structures across nested dictionaries in Python
Separate unique and common nested structures across nested dictionaries in Python

Time:10-19

I will have N different nested dictionaries where the different nested structures will have varying depth.

 d1 = {'A' : {'B' : 1, 'C': {'D' : 2 } } }

 d2 = {'A' : {'C' : {'D' : 2 } , 'E' : 3, 'F' : { 'G' : {'H' : 3 } } } }

 ..

What I want to do, is separate any common and unique structrures across ALL dictionaries.

What would be an efficient way of doing this?

If we would think that only d1 and d2 I would want the output to be

common_d = {'A' : { 'C' : {'D' : 2 } } }

unique_d1 = {'A' : {'B' : 1 } }
unique_d2 = {'A' : {'E' : 3, 'F' : { 'G' : {'H' : 3 } } } }

Would there be any way of doing this for N nested dictionaries?

CodePudding user response:

You have hierarchical (nested) dictionary values, with identifiers along each path from root down to leaf. Turn such paths into something hashable, such as tuple or str, and throw them into a set that describes d1.

Now iterate similarly over d2 and compute set intersection, noting any d2 paths that also appeared in d1. If you store sorted sets in text files, you will find they offer informative diff output.

Or just traverse d1's paths and probe d2 with similar path as you go.

  • Related