dict的嵌套键值总和 [英] Sum nested key values of dict

查看:90
本文介绍了dict的嵌套键值总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在Python 2.7中的示例字典:

This is my sample dictionary in Python 2.7:

sample = {'T1': {'P1': 20, 'P2': 100}, 'T2': {'P1': 60, 'P2': 50}}

我正在尝试使用键"P1"和"P2"对所有值求和以得到如下结果:

I am trying to sum up all the values with the key 'P1' and 'P2' to get a result like this:

reqResult = [80,150]

我将如何处理?

非常感谢.

推荐答案

您可以使用

>>> d = {'T1': {'P1': 20, 'P2': 100}, 'T2': {'P1': 60, 'P2': 50}}
>>> map(sum, zip(*[x.values() for x in d.values()]))
[150, 80]

这将首先计算内部字典,然后取出它们的值并将它们压缩在一起,最后将它们全部求和.

This will first compute the innner dicts, than take out their values and zip them togather, and finally sum them all.

或者,定义一个自定义函数并使用它:

Alternatively, define a custom function and use it:

>>> d = {'T1': {'P1': 20, 'P2': 100}, 'T2': {'P1': 60, 'P2': 50}}
>>> def sigma(list_of_dicts):
...     result = []
...     keys = list_of_dicts[0].keys()
...     for key in keys:
...         result.append(sum(x[key] for x in list_of_dicts))
...     return result
... 
>>> print sigma(d.values())
[150, 80]

这篇关于dict的嵌套键值总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆