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.