Combine dictionaries and add values

I have several dictionaries that I would like to combine, so if the key is in several dictionaries, the values ​​are added together. For instance:

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 looked at defaultdict and tried to come up with something. I am using Python 2.6.

+4
source share
3 answers

using 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} >>> 
+8
source

With most standard python 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 a default value of 0 is simple and easy.

+3
source

not 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} 
+2
source

All Articles