python Merge dictionaries

Question:

Suppose I have two dictionaries:

x={a: 4, is: 3, the :5}
y={i: 5, a:1, is:2, the: 1}

I want the result:

z={a:5, is:5, the: 6, i:5}

I used dict3 = {**dict1, **dict2}, but it seems its overwriting the other dictionary, not adding them up.

d3=dict()
print("Merge dic")
d3== {**dict1, **dict2}
for key in list(d3.keys()):
    print(key, ":", d3[key])
Asked By: Ayesha

||

Answers:

You can directly add Counters

>>> from collections import Counter
>>> x={'a': 4, 'is': 3, 'the' :5} 
>>> y={'i': 5, 'a':1, 'is':2, 'the': 1}
>>> Counter(x) + Counter(y)
Counter({'the': 6, 'a': 5, 'is': 5, 'i': 5})
>>> dict(Counter(x) + Counter(y))
{'a': 5, 'is': 5, 'the': 6, 'i': 5}
Answered By: Chris_Rands
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.