Add values from two dictionaries

Viewed 17405
dict1 = {a: 5, b: 7}
dict2 = {a: 3, c: 1}

result {a:8, b:7, c:1}

How can I get the result?

5 Answers

A quick dictionary comprehension that should work on any classes which accept the + operator. Performance might not be optimal.

{
    **dict1,
    **{ k:(dict1[k]+v if k in dict1 else v)
        for k,v in dict2.items() }
}
Here is another approach but it is quite lengthy!

d1 = {'a': 5, 'b': 7}
d2 = {'a': 3, 'c': 1}

d={}
for i,j in d1.items():
    for k,l in d2.items():
        if i==k:
            c={i:j+l}
            d.update(c)
for i,j in d1.items():
    if i not in d:
        d.update({i:j})
for m,n in d2.items():
    if m not in d:
        d.update({m:n})
Related