Python | Combine two dictionary adding values for common keys
Given two dictionary, the task is to combine the dictionaries such that we get the added values for common keys in 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 to do the task.
Method #1: Naive method
Python3
# Python program to combine two dictionary# adding values for common keys# initializing two dictionariesdict1 = {'a': 12, 'for': 25, 'c': 9}dict2 = {'Geeks': 100, 'geek': 200, 'for': 300}# adding the values with common keyfor key in dict2: if key in dict1: dict2[key] = dict2[key] + dict1[key] else: pass print(dict2) |
Output:
{'for': 325, 'Geeks': 100, 'geek': 200}
Method #2: Using collections.Counter()
Python3
# Python program to combine two dictionary# adding values for common keysfrom collections import Counter# initializing two dictionariesdict1 = {'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})
Method #3: Using itertools.chain()
Python3
# Python program to combine two dictionary# adding values for common keysimport itertoolsimport collections# initializing two dictionariesdict1 = {'a': 12, 'for': 25, 'c': 9}dict2 = {'Geeks': 100, 'geek': 200, 'for': 300}# using defaultdictCdict = 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:
{'for': 325, 'a': 12, 'geek': 200, 'Geeks': 100, 'c': 9}
Method #4: Using functools.reduce and dict comprehension
Python3
#Here is another way to combine dictionaies and#sum values of common keys (runs fast):from functools import reduce# creating three dictionaries in a listdict_seq = [ {'a': 1, 'b': 2, 'c': 3}, {'a':10, 'b': 20}, {'b': 100},]print(reduce(lambda d1,d2: {k: d1.get(k,0)+d2.get(k,0)for k in set(d1)|set(d2)}, dict_seq)) |
Output:
{'a': 11, 'b': 122, 'c': 3}



