Sometimes, we want to combine two dicts and add values for keys that appear in both with Python.
In this article, we’ll look at how to combine two dicts and add values for keys that appear in both with Python.
How to combine two dicts and add values for keys that appear in both with Python?
To combine two dicts and add values for keys that appear in both with Python, we can use the Counter
class.
For instance, we write
from collections import Counter
A = Counter({'a':1, 'b':2, 'c':3})
B = Counter({'b':3, 'c':4, 'd':5})
C = A + B
to create Counter
objects from the dicts.
Then we combine them into one and add the values with the given keys together with +
.
Conclusion
To combine two dicts and add values for keys that appear in both with Python, we can use the Counter
class.