简体   繁体   English

嵌套字典中值的百分比

[英]Percentage of values in a nested dictionary

I would like to obtain the percentage of values in a nested dictionary of the form:我想获得形式嵌套字典中值的百分比:

{'first': OrderedDict([('Jan', 2), ('Feb', 1)]), 'second': OrderedDict([('Jan', 3), ('Feb', 5)])}

The expected result should be like:预期的结果应该是这样的:

{'first': OrderedDict([('Jan', 40%), ('Feb', 16.6%)]), 'second': OrderedDict([('Jan', 60%), ('Feb', 83.3%)])}

The above result should be obtained as percentage: for the dictionary with key 'first':上述结果应以百分比形式获得:对于键为“first”的字典:

Jan : 2/5 *100 = 40%
Feb: 1/6 *100 = 16.6%

For the dictionary with key 'second':对于键为“秒”的字典:

Jan : 3/5 *100 = 60%
Feb: 5/6 *100 = 83.3%

Ordered Dictionary in python follows some of the traits as a normal dictionary you can update the value using.update('k': 'v') python 中的有序字典遵循一些特征作为普通字典,您可以使用.update('k': 'v') 更新值

for k, v in d.items(): v.update({'Jan': (v['Jan']/5)*100}) v.update({'Feb': (v['Feb']/6)*100})

The above answer is pretty good, but if you want to get the total values for all months you can try for loop two times, First to sum all values and second to update changes, like:上面的答案非常好,但如果你想获得所有月份的总值,你可以尝试两次循环,首先对所有值求和,然后更新更改,例如:

x={'first': OrderedDict([('Jan', 2), ('Feb', 1)]), 'second': OrderedDict([('Jan', 3), ('Feb', 5)])}

total = [0]*2
for k in x :
    for idx, month in enumerate(x[k]):
        total[idx] += x[k][month]

for k, v in x.items():
    for idx, month in enumerate(v) : 
        v.update({month:round((v[month]/total[idx])*100,2)})

print(x)

This will generate output as:这将生成 output 为:

{'first': OrderedDict([('Jan', 40.0), ('Feb', 16.67)]),
 'second': OrderedDict([('Jan', 60.0), ('Feb', 83.33)])}

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

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