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.
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]
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.