Match dictionary values back into dictionary

Viewed 39

I am performing a math operation on two dictionaries and I want to take the output of these dictionaries and map them back into another dictionary.

I have some working code that outputs my expected value but not into the key : value pair that I am interested in.

I have two dictionaries:

dict1
{'outer': {'word1':0.1234, 'word2':0.4321, 'word3':0.4567 } }
dict2
{'word1':2.222,'word3':3.567,'word2':2.123}

I have this code to multiply the values of word1 with word1 in their respective dictionaries:

new_dict=dict()
pkeys=dict1.keys()
for key in pkeys:
    for entry in dict1[key]:
        new_dict[entry]=  dict1[key][entry] * dict2[entry]

new_dict contains the correct output:'word1': 0.27419, but I can't seem to get it back into the format in

dict1: {'outer':{'word1':0.27419, 'word2':0.91734 } 
1 Answers

You can use the dict.setdefault method to initialize a sub-dict for new_dict under the current key in the iteration.

Change:

new_dict[entry]=  dict1[key][entry] * dict2[entry]

to:

new_dict.setdefault(key, {})[entry]=  dict1[key][entry] * dict2[entry]
Related