Search code examples
pythonpython-3.xloopsdictionarynested-loops

Division of nested dictionary


I have two dictionaries. one is a nested dictionary and another one is general dictionary. I want to do some divisions:

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

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

I want to use the inner dictionary values form dict1 to divided by the value of matching document in dict2. The expect output would be: enter code here

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

I tried using two for loop to run each dictionary, but values will be duplicate multiple times and I have no idea how to fix this? Does anyone has idea of how to achieve this goal? I would be appreciate it!``


Solution

  • You can achieve this using dictionary comprehension.

    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() }