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
# Python program to combine two dictionary # adding values for common keys # initializing two dictionaries dict1 = {'a': 12, 'for': 25, 'c': 9} dict2 = {'Geeks': 100, 'geek': 200, 'for': 300} # adding the values with common key for key in dict2: if key in dict1: dict2[key] = dict2[key] + dict1[key] else: pass print(dict2) |
chevron_right
filter_none
Output:
{'for': 325, 'Geeks': 100, 'geek': 200}
Method #2: Using collections.Counter()
# 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) |
chevron_right
filter_none
Output:
Counter({'for': 325, 'geek': 200, 'Geeks': 100, 'a': 12, 'c': 9})
Method #3: Using itertools.chain()
# 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)) |
chevron_right
filter_none
Output:
{'for': 325, 'a': 12, 'geek': 200, 'Geeks': 100, 'c': 9}
Recommended Posts:
- Python program to Swap Keys and Values in Dictionary
- Python | Find keys with duplicate values in dictionary
- Python | Test if dictionary contains unique keys and values
- Python | Split dictionary keys and values into separate lists
- Python | Combine the values of two dictionaries having same key
- Python | Add new keys to a dictionary
- Python | Minimum value keys in Dictionary
- Python Dictionary | keys() method
- Python | Add keys to nested dictionary
- Python | Get dictionary keys as a list
- Python | Remove Keys from dictionary starting with K
- Python dictionary with keys having multiple inputs
- Python | Extract specific keys from dictionary
- Python | Remove multiple keys from dictionary
- Python | Remove spaces from dictionary keys
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



