Sum nested key values of dict

橙三吉。 提交于 2020-01-16 07:06:29

问题


This is my sample dictionary in 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:

reqResult = [80,150]

How would I go about this?

Many thanks.


回答1:


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.

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]



回答2:


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]


来源:https://stackoverflow.com/questions/28345539/sum-nested-key-values-of-dict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!