Skip to content
Advertisement

How to calculate percentages inside nested dictionaries in Python

I have two dictionaries:

fruit = {'apple':15, 'mango':12, 'banana':16, 'kiwi':24}
people = {'sam':{'mango':3,'kiwi':12},
          'joy':{'apple':9, 'banana':10, 'kiwi':14},
          'bob':{'mango':8, 'apple':10, 'banana':12}}

For every key in the People dictionary, I want to calculate the percentage of values(fruits count) based on the fruit dictionary broken down by individual fruits and all fruits combined.

This is how the calculation is: {‘sam’:{‘mango’:3/12 = 0.25,’kiwi’:12/24 = 0.5, ‘total’: (3+12)/(12+24) = 0.41}

Finally, my output should look like this:

people = {'sam':{'mango':0.25,'kiwi':0.5, 'total':0.41},
          'joy':{'apple':0.6, 'banana':0.625, 'kiwi':0.58, 'total':0.6},
          'bob':{'mango':0.66, 'apple':0.66, 'banana':0.75, 'total':0.69}}

Can anyone help me how to calculate this?

Advertisement

Answer

You can use a loop, collect the numerator and denominator sums for the grand total and update each value:

for d in people.values():
    num = denom = 0
    for k,v in d.items():
        num += v          # sum values for total
        denom += fruit[k]
        d[k] = round(v/fruit[k],2)
    d['total'] = round(num/denom,2)

NB. I’m assuming here that all keys exist in fruit. If this in not guaranteed use the get method with a default value.

Output:

{'sam': {'mango': 0.25, 'kiwi': 0.5, 'total': 0.42},
 'joy': {'apple': 0.6, 'banana': 0.62, 'kiwi': 0.58, 'total': 0.6},
 'bob': {'mango': 0.67, 'apple': 0.67, 'banana': 0.75, 'total': 0.7}}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement