简体   繁体   English

求和dict的嵌套键值

[英]Sum nested key values of dict

This is my sample dictionary in Python 2.7: 这是我在Python 2.7中的示例字典:

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

I am trying to sum up all the values with the key 'P1' and 'P2' to get a result like this: 我试图用键'P1'和'P2'来总结所有值,得到这样的结果:

reqResult = [80,150]

How would I go about this? 我该怎么做?

Many thanks. 非常感谢。

You can use 您可以使用

>>> 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. 这将首先计算内在的dicts,而不是取出它们的值并将它们压缩,最后将它们全部加起来。

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]

From the tags on your question, you seem to be looking for a list-comprehension to do this. 从您问题的标签,您似乎正在寻找列表理解来做到这一点。 As is often the case, they can be somewhat difficult to read — but here's one: 通常情况下,它们可能有点难以阅读 - 但这里有一个:

from collections import Counter

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

reqResult = [v[1] for v in sorted(reduce(lambda c, d: (c.update(d), c)[1],
                                         sample.values(), Counter()).items())]

print reqResult  # --> [80, 150]

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

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