Merge Python dictionaries add values of common keys

In this post, we are going to learn about Merge Python dictionaries add values of common keys with code examples. While working with huge data samples we often need to merge different data samples.

In this article we will cover different techniques to merge the dictionaries that will help you in the problem related to data handling. So let us begin with our task for today.

1. ** merge dictionaries adding values of common keys

In this code example, we are adding values of two dictionaries by common key using for loop and unpacking operator(**). If the key exists in both dictionaries then the values of common keys will be added as the result value.

Pass: Pass in python is used for none operation, if we do not want to execute in the loop or if-else statement we can use Pass. Here we are using pass statement in else. Here is the code example to understand it better:

merge dictionaries adding values of common keys

#Python Program to merge dictionaries adding values of common keys

dict_sub = {'math':100,'Eng':100,'Chem':98,'students':['jack','mack']}
dict_sub1 = {'math':100,'Eng':100}

for key in dict_sub1:
   if key in dict_sub:
      dict_sub1[key] = dict_sub1[key]+dict_sub[key]
      
   else:
    pass

add_common_key_dict = {**dict_sub, **dict_sub1}
print('addition of common keys values in dictionary =\n',add_common_key_dict)


Output

addition of common keys values in dictionary =
 {'math': 200, 'Eng': 200, 'Chem': 98, 'students': ['jack', 'mack']}

Make above code Reusable by defining function

Here we are using the above code and defining a function to make code resusable.

#Python Program to merge dictionaries adding values of common keys
dict_sub = {'math':100,'Eng':100,'Chem':98,'students':['jack','mack']}
dict_sub1 = {'math':100,'Eng':100}

def add_common_keys(first_Dict,second_dict):
  for key in second_dict:
     if key in first_Dict:
      second_dict[key] = second_dict[key]+first_Dict[key]
      
     else:
      pass

  add_common_key_dict = {**dict_sub, **dict_sub1}

  print('addition of common keys values in dictionary =\n',add_common_key_dict)

#use function
add_common_keys(dict_sub1,dict_sub)

Output

addition of common keys values in dictionary =
 {'math': 100, 'Eng': 100, 'Chem': 98, 'students': ['jack', 'mack']}

2. collection.Counter() to merge Python dictionaries adding values of common keys

counter() is a function present in the collection module of Python. It is used to combine two dictionaries and add the values of common keys. We will use counter() to adds values for common keys of dictionaries.

Code example

#Python Program to merge dictionaries adding values of common keys
from collections import Counter
dict_sub = {'math':100,'Eng':100,'Chem':98}
dict_sub1 = {'math':100,'Eng':100}

#defining a function
def add_common_keys(first_dict,second_dict):
  
  #combining two dictionaries
  add_common_val_dict = Counter(first_dict) + Counter(second_dict)


 
  print('addition of common keys values in dictionary =\n',add_common_val_dict)
  
 
add_common_keys(dict_sub1,dict_sub)

Output

addition of common keys values in dictionary =
 Counter({'math': 200, 'Eng': 200, 'Chem': 98})

3.Update() Method to merge dictionaries

In this example, we are using the inbuilt dictionary update() method to add values of common keys of dictionaries. This is a fast method as compare to Counter().

Code example

#Python Program to merge dictionaries adding values of common keys

dict_sub = {'math':100,'Eng':100,'Chem':98,'students':['jack','mack']}
dict_sub1 = {'math':100,'Eng':100}

#defining a function

def add_common_keys(first_dict,second_dict):
  
  #combining two dictionaries
  first_dict.update(second_dict)


 
  print('addition of common keys values in dictionary =\n',first_dict)
  
 
add_common_keys(dict_sub1,dict_sub)

Output

addition of common keys values in dictionary =
 {'math': 100, 'Eng': 100, 'Chem': 98, 'students': ['jack', 'mack']}

4. itertools.chain() to merge dictionaries adding values of common keys

In this code example, we are merging the dictionaries by using the chain() method which is present in the itertools module. We are merging both dictionaries by iterate over the values and key and adding values of the common dictionary.

Code example

#Python Program to merge dictionaries adding values of common keys
import itertools  
import collections
dict_sub = {'math':100,'Eng':100,'Chem':98}
dict_sub1 = {'math':100,'Eng':100}

common_vals= collections.defaultdict(int)
  

#defining a function

def add_common_keys(first_dict,second_dict):  
  #combining two dictionaries
  for key, val in itertools.chain(first_dict.items(), second_dict.items()): 
    common_vals[key] += val   
  print('addition of common keys values in dictionary =\n',dict(common_vals))
  
 
add_common_keys(dict_sub1,dict_sub)

Output

addition of common keys values in dictionary =
 {'math': 200, 'Eng': 200, 'Chem': 98};

Conclusion:

In this post, we have understood how Python merges dictionaries by adding values of common keys. We learned the techniques by using different ways includes update(), chain(), and counter() and for a loop. We hope you will find it useful in your programs.

Happy Learning!!