Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python Merge dictionaries

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading