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 from the collections
module.
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
print(C)
We create Counter
instances from 2 dicts and assign them to A
and B
respectively.
Then we add the values of each dict entry together by using the +
operator and assign the result to C
.
Therefore, we see that C
is Counter({'c': 7, 'b': 5, 'd': 5, 'a': 1})
from what we printed.
Conclusion
To combine two dicts and add values for keys that appear in both with Python, we can use the Counter
class from the collections
module.