简体   繁体   English

如何计算 Python 中嵌套字典内的百分比

[英]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.对于 People 字典中的每个键,我想根据按单个水果和所有水果组合的水果字典计算值的百分比(水果计数)。

This is how the calculation is: {'sam':{'mango':3/12 = 0.25,'kiwi':12/24 = 0.5, 'total': (3+12)/(12+24) = 0.41}计算方式如下: {'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:最后,我的 output 应该是这样的:

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?谁能帮我计算一下?

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 .我在这里假设所有键都存在于fruit中。 If this in not guaranteed use the get method with a default value.如果这不能保证,请使用带有默认值的get方法。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM