How to use collections.Counter()  to Combine two dictionary adding values for common keys In Python

Here we are using the collections module to calculate the combination of two dictionaries by adding the values for common keys.

Python3




# Python program to combine two dictionary
# adding values for common keys
from collections import Counter
 
# initializing two dictionaries
dict1 = {'a': 12, 'for': 25, 'c': 9}
dict2 = {'Geeks': 100, 'geek': 200, 'for': 300}
 
 
# adding the values with common key
         
Cdict = Counter(dict1) + Counter(dict2)
print(Cdict)


Output:

Counter({'for': 325, 'geek': 200, 'Geeks': 100, 'a': 12, 'c': 9})

The time complexity of the given program is O(m+n), where m and n are the number of elements in dict1 and dict2, respectively.

The auxiliary space complexity of the program is O(k), where k is the number of unique keys in both dictionaries. 

Python | Combine two dictionary adding values for common keys

Given two dictionaries, the task is to combine the dictionaries such that we get the added values for common keys in the resultant dictionary. 
Example: 

Input: dict1 = {'a': 12, 'for': 25, 'c': 9}
       dict2 = {'Geeks': 100, 'geek': 200, 'for': 300}

Output: {'for': 325, 'Geeks': 100, 'geek': 200}

Let’s see some of the methods on How to  Combine two dictionaries by adding values for common keys in Python. 

Similar Reads

Naive Method to Combine two dictionary adding values for common keys

Here we are iterating over the dictionaries and adding the values for the same keys....

Using Union Method  to Combine two dictionary adding values for common keys

...

Using collections.Counter()  to Combine two dictionary adding values for common keys

Here we are using the set union method and with the help of get() function we are fetching the value for that particular keys....

Using itertools.chain()  to Combine two dictionary adding values for common keys

...

Using functools.reduce and dict comprehension to Combine two dictionary adding values for common keys

Here we are using the collections module to calculate the combination of two dictionaries by adding the values for common keys....