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.
Python3
# 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) |
Output:
{'Geeks': 100, 'geek': 200, 'for': 325}
Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), to store the keys and values in dictionary.
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.