Home > Back-end >  How to calculate percentages inside nested dictionaries in Python
How to calculate percentages inside nested dictionaries in Python

Time:08-26

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?

CodePudding user response:

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

CodePudding user response:

Try:

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},
}

out = {
    k: {
        **{f: amount / fruit[f] for f, amount in v.items()},
        "total": sum(v.values()) / sum(fruit[f] for f in v),
    }
    for k, v in people.items()
}

print(out)

Prints:

{
    "sam": {"mango": 0.25, "kiwi": 0.5, "total": 0.4166666666666667},
    "joy": {
        "apple": 0.6,
        "banana": 0.625,
        "kiwi": 0.5833333333333334,
        "total": 0.6,
    },
    "bob": {
        "mango": 0.6666666666666666,
        "apple": 0.6666666666666666,
        "banana": 0.75,
        "total": 0.6976744186046512,
    },
}
  • Related