Skip to content Skip to sidebar Skip to footer

Merge Dictionaries And Add Values

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:

Solution 1:

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}
>>>

Solution 2:

With the very most python standard functions and libraries:

dlst = [d1, d2, d3]
foriin dlst:
    forx,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.

Solution 3:

without importing anything. .

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

output:

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

Post a Comment for "Merge Dictionaries And Add Values"