Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge dictionaries and add values

Tags:

python

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.

like image 834
user1728853 Avatar asked Dec 11 '22 16:12

user1728853


1 Answers

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}
>>>
like image 102
sloth Avatar answered Jan 12 '23 21:01

sloth