Oleksandr Pryhoda
Oleksandr Pryhoda

Reputation: 68

Python - add one dictionary to another

I want to update one dictionary with another in Python, but if there are some same arguments, their values should be added. For example:

a = {"word_1" : 1, "word_2": 2}
b = {"word_2" : 5, "word_3": 7}

Output must be:

{"word_1" : 1, "word_2": 7, "word_3": 7}

I have googled a lot, but in most answers values rewrites, I want to add them Here is my solution:

    for i in a.keys():
        if i in b.keys():
            b[i] += a[i]
        else:
            b[i] = a[i]

Is there most efficient way to do it?

Upvotes: 1

Views: 2236

Answers (2)

shizhz
shizhz

Reputation: 12531

How about:

{k: a.get(k, 0) + b.get(k, 0) for k in set(list(a.keys()) + list(b.keys()))}

Upvotes: 4

Patrick Haugh
Patrick Haugh

Reputation: 61063

Use a Counter, which is a special kind of dictionary for counting objects.

from collections import Counter

a = Counter({"word_1" : 1, "word_2": 2})
b = Counter({"word_2" : 5, "word_3": 7})
print(a + b)

prints

Counter({'word_2': 7, 'word_3': 7, 'word_1': 1})

Upvotes: 10

Related Questions