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])
Answers:
You can directly add Counter
s
>>> 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}
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])
You can directly add Counter
s
>>> 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}