4

I have several dictionaries which I'd like to combine such that if a key is in multiple dictionaries the values are added together. For example:

d1 = {1: 10, 2: 20, 3: 30}
d2 = {1: 1, 2: 2, 3: 3}
d3 = {0: 0}

merged = {1: 11, 2: 22, 3: 33, 0: 0}

What is the best way to do this in Python? I was looking at defaultdict and trying to come up with something. I'm using Python 2.6.

user1728853
  • 2,607
  • 4
  • 30
  • 31
  • 1
    None of these are really duplicates. – sloth Mar 28 '13 at 09:12
  • @Bakuriu: I think both of those are different -- the first one doesn't do the Counter-like arithmetic, and the second one doesn't seem to mind the loss of the keys with zero values. (Which actually surprises me -- up until today I'd never known that `Counter` objects dropped the zero-valued keys when doing arithmetic.) – DSM Mar 28 '13 at 09:13
  • [Here's](http://hg.python.org/cpython/file/2.7/Lib/collections.py#l598) the relevant line. – sloth Mar 28 '13 at 09:16

3 Answers3

8

using a defaultdict:

>>> d = defaultdict(int)
>>> for di in [d1,d2,d3]:
...   for k,v in di.items():
...     d[k] += v
...
>>> dict(d)
{0: 0, 1: 11, 2: 22, 3: 33}
>>>
sloth
  • 99,095
  • 21
  • 171
  • 219
3

With the very most python standard functions and libraries:

dlst = [d1, d2, d3]
for i in dlst:
    for x,y in i.items():
        n[x] = n.get(x, 0)+y

Instead of using if-else checks, using dict.get with default value 0 is simple and easy.

Mp0int
  • 18,172
  • 15
  • 83
  • 114
  • That *might* be a bit faster that `defaultdict` usage, but iw would be so small and quite ignorable. – Mp0int Mar 28 '13 at 09:36
2

without importing anything. .

d4={}
for d in [d1,d2,d3]:
    for k,v in d.items():
        d4.setdefault(k,0)
        d4[k]+=v
print d4

output:

{0: 0, 1: 11, 2: 22, 3: 33}
namit
  • 6,780
  • 4
  • 35
  • 41