Home > Enterprise >  Generate binary values within nested dictionary from two dictionaries
Generate binary values within nested dictionary from two dictionaries

Time:06-14

two input dictionaries are: input dictionary 1

d1 = {'ad':['gf','tr','st'],'ft':['te','gr','mf']}

input dictionary 2

d2 = {'ad':['te','mr','lr','kr','er'],'ft':['ty','yr','qf','fg','jh']}

required output dictionary is

output={'ad':{'gf':1,'tr':1,'st':1,'te':0,'mr':0,'lr':0,'kr':0,'er':0},
    'ft':{'te':1,'gr':1,'mf':1,'ty':0,'yr':0,'qf':0,'fg':0,'jh':0}}

Is there anyway to produce this output dictionary from these two input dictionaries. In output, if the inner dictionary value belong to dictionary 1 then its value is 1 in output dictionary. If it belongs to dictionary 2 then its value is 0.

CodePudding user response:

d1 = {'ad':['gf','tr','st'],'ft':['te','gr','mf']}
d2 = {'ad':['te','mr','lr','kr','er'],'ft':['ty','yr','qf','fg','jh']}

output = {}
for k in d1:
    output[k] = {k2: 1 for k2 in d1[k]}
    output[k].update({k2:0 for k2 in d2[k]})

output:

{'ad': {'gf': 1, 'tr': 1, 'st': 1, 'te': 0, 'mr': 0, 'lr': 0, 'kr': 0, 'er': 0}, 'ft': {'te': 1, 'gr': 1, 'mf': 1, 'ty': 0, 'yr': 0, 'qf': 0, 'fg': 0, 'jh': 0}}
  • Related