Home > Mobile >  Generate pairs from nested dictionaries
Generate pairs from nested dictionaries

Time:04-25

Is there any way to generate pairs from the nested dictionary in python? I have an input dictionaries:

d1 = {'AB':{'BCA':1.2, 'CBA':2.41, 'BCD':3.81},
     'DA':{'ADA':1.3, 'BMA':1.41, 'DMA':1.81}}
d2 = { 'AB':{'MNA':1.3,'CMA':1.41,'BCD':2.41},
      'DA':{'ADA':1.8, 'BMA':1.81, 'BTA':1.42}}

Expected output:

d3= {('AB'-'BCA'):(1.2,new),
     ('AB'-'CBA'):(2.41,new),
     ('AB'-'BCD):(3.81,2.41),
     ('AB'-'MNA'):(new,1.3),
     ('AB'-'CMA'):(new,1.41),
     ('DA'-'ADA'):(1.3,1.8),
     ('DA'-'BMA'):(1.41,1.81),
     ('DA'-'DMA'):(1.81,new),
     ('DA'-'BTA'): (new,11.42)}

Is there any way to produce this output from input nested dictionaries? if the keys of inner dictionary are not present within another inner dictionary then in this case it replace it with 'new' and maintain the other for dictionary?

CodePudding user response:

You can iterate the top-level keys in d1, finding all the keys in the second level dicts with that key in d1 and d2, and then build your new dict using dict.get with a default value of 'new' to fill in empty slots:

d3 = {}
for l1key in d1:
    for l2key in set(d1[l1key].keys()) | set(d2[l1key].keys()):
        d3[f'{l1key} - {l2key}'] = (d1[l1key].get(l2key, 'new'), d2[l1key].get(l2key, 'new'))

Output:

{
 'AB - CBA': (2.41, 'new'),
 'AB - MNA': ('new', 1.3),
 'AB - BCA': (1.2, 'new'),
 'AB - BCD': (3.81, 2.41),
 'AB - CMA': ('new', 1.41),
 'DA - BMA': (1.41, 1.81),
 'DA - BTA': ('new', 1.42),
 'DA - DMA': (1.81, 'new'),
 'DA - ADA': (1.3, 1.8)
}
  • Related