Python - Combine two dictionary adding values for common keys


When analyzing data with python we come across situations when we have to merge two dictionaries in such a way that we add the values of those elements whose keys have equal values. In this article we will see such two dictionaries getting added.

With For loop and | Operator

In this approach we design a for loop to check for the presence of the value of the key in both the dictionaries and then add them. Finally we merge the two dictionaries using the | operator available for the dictionaries.

Example

dictA = {'Mon': 23, 'Tue': 11, 'Sun': 6}
dictB = {'Wed': 10, 'Mon': 12, 'Sun': 4}

# Add with common key
for key in dictB:
   if key in dictA:
      dictB[key] = dictB[key] + dictA[key]
   else:
      pass
res = dictA | dictB
print(res)

Running the above code gives us the following result −

Output

{'Mon': 35, 'Tue': 11, 'Sun': 10, 'Wed': 10}

Using Counter

The Counter function from the Collections module can be directly applied to merge the two dictionaries which preserves the keys. And in turn adds the values at the matching keys.

Example

from collections import Counter
dictA = {'Mon': 23, 'Tue': 11, 'Sun': 6}
dictB = {'Wed': 10, 'Mon': 12, 'Sun': 4}

res = Counter(dictA) + Counter(dictB)
print(res)

Running the above code gives us the following result −

Output

Counter({'Mon': 35, 'Tue': 11, 'Sun': 10, 'Wed': 10})

Updated on: 28-Dec-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements