0

What would be the most efficient way to sum across dictionaries within a large dictionary in Python?

I am finding similar posts, but not exactly what I am looking for. For example, there is a post for dict in a list: Python: Elegantly merge dictionaries with sum() of values. There are other stuffs too, but not exactly for dict within a dict.

Example code would be:

a={}
a["hello"]={'n': 1,'m': 2,'o': 3}
a["bye"]={'n': 2,'m': 1,'o': 0}
a["goodbye"]={'n': 0,'m': 2,'o': 1}

And the output I need would be:

{'n': 3,'m': 5,'o': 4}

Please, help! Many thanks!

Community
  • 1
  • 1
striatum
  • 1,428
  • 3
  • 14
  • 31

2 Answers2

4

Using collections.Counter

>>> a = {}
>>> a["hello"]={'n': 1,'m': 2,'o': 3}
>>> a["bye"]={'n': 2,'m': 1,'o': 0}
>>> a["goodbye"]={'n': 0,'m': 2,'o': 1}
>>> import collections
>>> result = collections.Counter()
>>> for d in a.values():
...     result += collections.Counter(d)
...
>>> result
Counter({'m': 5, 'o': 4, 'n': 3})
>>> dict(result)
{'m': 5, 'o': 4, 'n': 3}

Using collections.Counter with sum (similar to the answer in the link you provided):

>>> a = ...
>>> sum(map(collections.Counter, a.values()), collections.Counter())
Counter({'m': 5, 'o': 4, 'n': 3})
falsetru
  • 357,413
  • 63
  • 732
  • 636
0

You can use a collections.defaultdict:

>>> a = {'bye': {'m': 1, 'o': 0, 'n': 2}, 'hello': {'m': 2, 'o': 3, 'n': 1}, 'goodbye': {'m': 2, 'o': 1, 'n': 0}}
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for v in a.values():                                              
...     for x, y in v.iteritems():                                              
...             d[x] += y
... 
>>> print d
defaultdict(<type 'int'>, {'m': 5, 'o': 4, 'n': 3})
TerryA
  • 58,805
  • 11
  • 114
  • 143