Skip to content Skip to sidebar Skip to footer

Sum Nested Key Values Of Dict

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' t

Solution 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}}>>>defsigma(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]

Solution 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 insorted(reduce(lambda c, d: (c.update(d), c)[1],
                                         sample.values(), Counter()).items())]

print reqResult  # --> [80, 150]

Post a Comment for "Sum Nested Key Values Of Dict"