Skip to content
Advertisement

How to calculate percentages inside nested dictionaries in Python

I have two dictionaries:

JavaScript

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:

JavaScript

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:

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement