Python – Division of nested dictionaries

Division of nested dictionaries… here is a solution to the problem.

Division of nested dictionaries

I have two dictionaries. One is a nested dictionary and the other is a generic dictionary. I would like to do some division:

dict1 = {'document1': {'a': 3, 'b': 1, 'c': 5}, 'document2': {'d': 2, 'e': 4} }

dict2 = {'document1': 28, 'document2': 36}

I want to divide the internal dictionary value in dict1 by the value in dict2 that matches the document. The expected output will be:
Enter the code here

dict3 = {'document1': {'a': 3/28, 'b': 1/28, 'c': 5/28}, 'document2': {'d': 2/36, 'e': 4/36}}

I

tried running each dictionary with two for loops, but the values are repeated multiple times and I don’t know how to fix this? Does anyone know how to achieve this goal? I would appreciate it!”

Solution

You can use dictionary comprehension to achieve this.

dict3 = {} # create a new dictionary

# iterate dict1 keys, to get value from dict2, which will be used to divide dict 1 values

for d in dict1:
       y  = dict2[d] 
       dict3[d] = {k:(v/y) for k, v in dict1[d].items() }

Related Problems and Solutions