Skip to content Skip to sidebar Skip to footer

Summing Items In Nested Dictionary With Different Keys

I have a nested dictionary along the lines of: {'apple': {'a': 1, 'b': 4, 'c': 2}, 'orange': {'a': 4, 'c': 5}, 'pear': {'a': 1, 'b': 2}} What I want to do is get rid of the o

Solution 1:

You can use the Counter class:

>>> from collections import Counter

>>> d = {'apple': {'a': 1, 'b': 4, 'c': 2}, 'orange': {'a': 4, 'c': 5}, 'pear': {'a': 1, 'b': 2}}
>>> sum(map(Counter, d.values()), Counter())
Counter({'c': 7, 'a': 6, 'b': 6})

Solution 2:

from collections importdefaultdictd= defaultdict(int)
for dct in yourdict.values():
    for k,v in dct.items():
        d[k] += v

The main advantage of this answer is that it works back to python2.5. For python2.7+, see the solutions posted by @DSM and @BigYellowCactus.

Solution 3:

Here is another collections.Counter solution, it isn't a one-liner like the others but I think it is cleaner:

from collections importCounterd= {'apple': {'a': 1, 'b': 4, 'c': 2}, 'orange': {'a': 4, 'c': 5}, 'pear': {'a': 1, 'b': 2}}

counts = Counter()
for v in d.values():
    counts.update(v)

Solution 4:

The Counter object is designed to make things like this very easy:

>>> from collections import Counter
>>> d = {'apple': {'a': 1, 'b': 4, 'c': 2}, 'orange': {'a': 4, 'c': 5}, 'pear': {'a': 1, 'b': 2}}
>>> sum((Counter(v) for v in d.itervalues()), Counter())
Counter({'c': 7, 'a': 6, 'b': 6})

Post a Comment for "Summing Items In Nested Dictionary With Different Keys"