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

Here we are using the itertools module to Combine two dictionary by adding values for common keys using the chain().

Python3




# Python program to combine two dictionary
# adding values for common keys
import itertools
import collections
 
# initializing two dictionaries
dict1 = {'a': 12, 'for': 25, 'c': 9}
dict2 = {'Geeks': 100, 'geek': 200, 'for': 300}
 
# using defaultdict
Cdict = collections.defaultdict(int)
 
# iterating key, val with chain()
for key, val in itertools.chain(dict1.items(), dict2.items()):
    Cdict[key] += val
     
print(dict(Cdict))


Output:

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

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....