Learn Python – Merge two Dictionaries in Python- Basic and advance

Python Dictionary is a facts structure that incorporates all factors in key-value pairs. Each key-value pair maps the keys with their associative value. Hence it is also regarded as the associative array of Python Dictionary. All the elements of the dictionary are enclosed within curly braces {}. Furthermore, we use a colon (:) symbol in between the key-value pairs that separate every key from its associative value. Dictionary factors can be organized in any order and modified dynamically in the Python program. In this topic, we will analyze how to merge two dictionaries using more than a few techniques of Python dictionaries.

Merge two dictionaries using for loop

Here we use a For loop that iterates the first dictionary and concurrently adds entries to every other dictionary to merge them.

Let’s reflect onconsideration on a application to merge the given dictionaries using the For loop.

forDict.py

dict1 = { 'Alexandra' : 27,      # given the first dictionary in key-value pairs  
            'Shelina Gomez' : 22,  
            'James' : 29,  
            'Peterson' : 30  
                        }   
dict2 = {  
            'Jasmine' : 19,      # given the second dictionary in key-value pairs  
            'Maria' : 26,  
            'Helena' : 30  
}                          
print("Before merging the two dictionary ")  
print("Dictionary No. 1 is : ", dict1) # print the dict1  
print("Dictionary No. 1 is : ", dict2)  # print the dict2  
  
dict3 = dict1.copy()  # Copy the dict1 into the dict3 using copy() method  
  
for key, value in dict2.items():  # use for loop to iterate dict2 into the dict3 dictionary  
    dict3[key] = value  
  
print("After merging of the two Dictionary ")  
print(dict3)    # print the merge dictionary  

Output:

Before merging the two dictionary
Dictionary No. 1 is :  {'Alexandra': 27, 'Selina Gomez': 22, 'James': 29, 'Peterson': 30}
Dictionary No. 1 is :  {'Jasmine': 19, 'Maria': 26, 'Helena': 30}
After merging of the two Dictionary
{'Alexandra': 27, 'Selina Gomez': 22, 'James': 29, 'Peterson': 30, 'Jasmine': 19, 'Maria': 26, 'Helena': 30}

Merge two dictionaries using the update() method

The update() technique is used in the Python Dictionary to update the present day dictionary with the second dictionary’s content. Using the update() method, we can keep away from creating a 0.33 dictionary to save the first dictionary element and then update the 2nd dictionary element.

Let’s think about a software to merge the given dictionaries in Python besides creating the third dictionary.

Update1.py

d1 = {'Actress ' : 'Jasmine Wiley',       
    'Cricketer' : 'Nicholas Pooran',  
    'Basketball': 'Jordan',  
    'Football' : 'Zindane'  
}  
  
# Defines the d2 dictionary   
d2 = {'Tennis ' : 'Maria',  
    'Stadium  ' : 'Amsterdam',  
    'Basketball' : 'Washington',  
    'Actress' : 'Elizabeth'}  
  
d1.update(d2) # append the d2 dictionary items into the d1 dictionary.  
print( "Merge two dictionaries :")  
print(d1) # print the merge dictionary   

Output:

{'Actress ': 'Jasmine Wiley', 'Cricketer': 'Nicholas Pooran', 'Basketball': 'Washington', 'Football': 'Zindane', 'Tennis ': 'Maria', 'Stadium  ': 'Amsterdam', 'Actress': 'Elizabeth'}

Merge two dictionaries in Python the use of the Function

Let’s think about a software to merge the given dictionaries in Python the usage of the update() approach in function.

proFun.py

def merge_twoDict(a, b): # define the merge_twoDict() function  
    return (a.update(b)) # append the second dictionary (b) to the first dictionary (a)   
  
a = {'USA' : 'New York',  
      'Jermany' : 'Jakarta',  
      'England' : 'London' }  
b = {  
    'India' : 'Delhi',  
    'Russia' : 'Russian',  
    'Australia' : 'Sydney'  
}            
merge_twoDict(a, b) # pass two dictionaries to merge_twoDict() function  
print("Merged Dictionaries is : ")  
print(a) # print the merge dictionaries   

Output:

Merged Dictionaries is :
{'USA': 'New York', 'Germany': 'Jakarta', 'England': 'London', 'India': 'Delhi', 'Russia': 'Russian', 'Australia': 'Sydney'}

Merge two dictionaries using update() technique when both dictionaries having identical keys

Let’s consider a software to merge the given dictionaries in Python the use of the update() method when each dictionaries contains equal keys.

sameDict.py

# Defines the d1 dictionary in key- value pairs  
d1 = {      
    'Cricketer' : 'Nicholas Pooran',  
    'Basketball': 'Jordan',  
    'Football' : 'Zindane',  
    'Actress' : 'Jasmine Wiley'   
    }  
  
# Defines the d2 dictionary in key- value pairs  
d2 = { 'Tennis' : 'Maria',  
    'Stadium' : 'Amsterdam',  
    'Basketball' : 'Washington',  
    'Actress' : 'Elizabeth' }  
  
d1.update(d2) # append the d2 dictionary items into the d1 dictionary.  
print( "Merge two dictionaries :")  
print(d1) # print the merge dictionary  

Output:

Merge two dictionaries :
{'Cricketer': 'Nicholas Pooran', 'Basketball': 'Washington', 'Football': 'Zindane', 'Actress': 'Elizabeth', 'Tennis': 'Maria', 'Stadium': 'Amsterdam'}

We have the two equal keys (Actress and Basketball) in each the dictionaries. When we function the update method, the cutting-edge value of the 2nd dictionary overrides the first dictionary’s old values. When the d1 dictionary is executed, it prints Washington and Elizabeth values for the key Actress and Basketball instead of Jasmine Wiley and Jordan.

Merge two dictionaries the use of Copy() and Update() Method

In this method, we reproduction all the factors of the first dictionary (d1) factors using the copy() characteristic and then assign the copied information into the different dictionary (d3). After that, we update the dictionary d3 with the d2 dictionary using the update() function.

Let’s consider a application to merge the given dictionaries the usage of the replica and update() method in Python.

CopyUpdate.py

dict1 = {             
    'Student' : 'Butler',  
    'Course' : 'Computer Science',  
    'Address' : 'Los Angeles'  
}  
  
  
dict2 = {  
    'Teacher' : 'Rosy',  
    'Subject' : 'Computer Science'  
}  
  
# Use Copy() function to copy the dict1 into the dict3  
dict3 = dict1.copy()  
print("Before Merge")  
print(dict3) # print dict3 dictionary  
  
# use update() dictionary function to update the dict3 using the dict2.  
dict3.update(dict2)  
  
print("After Merge of the two Dictionary is : ", dict3)  

Output:

Before Merge
{'Student': 'Butler', 'Course': 'Computer Science', 'Address': 'Los Angeles'}
After Merge of the two Dictionary is :  {'Student': 'Butler', 'Course': 'Computer Science', 'Address': 'Los Angeles', 'Teacher': 'Rosy', 'Subject': 'Computer Science'}

Merge two dictionaries using the ** operator – Unpacking Operator

The unpacking operator used to mix two or extra dictionaries inside a single expression and stored them in a third dictionary.

Syntax:

Res = { **dictF1, ** dictF2 }  

Let’s reflect onconsideration on a application to merge the given dictionaries using the ** operator in Python.

Unpack.py

dict1 = {             
    'Student' : 'Butler',  
    'Course' : 'Computer Science',  
    'Address' : 'Los Angeles'  
}  
  
dict2 = {  
    'Teacher' : 'Rosy',  
    'Subject' : 'Computer Science'  
}  
  
dict3 = {  
    'Country' : 'England',  
    'State' : 'California',  
    'mob' : +3487434      
}  
  
# Use ** operator or Unpack Operator  
d5 = {**dict1, **dict2}  
print("Merge two dictionaries", d5) # Merge two dictionaries  
  
d4 = {  
    **dict1, **dict2, **dict3   
    }  
print("Merge more than two dictionaries", d4) # Merge multiples dictionaries  

Output:

Merge two dictionaries {'Student': 'Butler', 'Course': 'Computer Science', 'Address': 'Los Angeles', 'Teacher': 'Rosy', 'Subject': 'Computer Science'}
Merge more than two dictionaries {'Student': 'Butler', 'Course': 'Computer Science', 'Address': 'Los Angeles', 'Teacher': 'Rosy', 'Subject': 'Computer Science', 'Country': 'England', 'State': 'California', 'mob': 3487434}

Merge two dictionaries the usage of the dict() constructor

A dict() constructor technique is similar to the copy() and update() in Python Dictionary. A dict() constructor copies the first dictionary factors to the new dictionary and then followed an update() method to replace the new dictionary by the 2d dictionary’s element.

Let’s reflect onconsideration on a application to merge the given dictionaries the use of the dict() technique in Python.

Dict.py

dict1 = {             
    'Student' : 'Butler',  
    'Course' : 'Computer Science',  
    'Address' : 'Los Angeles'  
}  
  
dict2 = {  
    'Teacher' : 'Rosy',  
    'Subject' : 'Computer Science'  
}  
  
# Use dict() constructor  
d3 = dict(dict1)  
print("Before Merge", d3)  
d3.update(dict2)  
print("Merge two dictionaries", d3) # Merge two dictionaries    

Output:

Before Merge {'Student': 'Butler', 'Course': 'Computer Science', 'Address': 'Los Angeles'}
Merge two dictionaries {'Student': 'Butler', 'Course': 'Computer Science', 'Address': 'Los Angeles', 'Teacher': 'Rosy', 'Subject': 'Computer Science'}

Merge two dictionaries using the dict() constructor and **kwargs

It is a shortcut technique of dict () constructor that uses a kwargs (**) operator to map one dictionary to every other with the help of dict () method.

Syntax:

D3 = dict(dict1, **dict)  

Let’s think about a program to merge two dictionaries the usage of the dict() constructor and **kwargs operator in Python.

Kwarg.py

dict1 = {             
    'Student' : 'Butler',  
    'Course' : 'Computer Science',  
    'Address' : 'Los Angeles'  
}  
  
# Second dictionary is:  
dict2 = {  
    'Teacher' : 'Rosy',  
    'Subject' : 'Computer Science'  
}  
  
  
# Use dict() constructor  
d3 = dict(dict1, **dict2)  
  
print("Merge two dictionaries", d3) # Merge two dictionaries  

Output:

Merge two dictionaries {'Student': 'Butler', 'Course': 'Computer Science', 'Address': 'Los Angeles', 'Teacher': 'Rosy', 'Subject': 'Computer Science'}

Merge two dictionaries the use of the Collections – ChainMap characteristic

ChainMap is a collection of more than one dictionaries that return a single dictionary. It is a faster technique to create a new dictionary and run multiple files compared to the update () method. To merge the two dictionaries in Python, we need to import the ChainMap from collections. In ChainMap() function, we bypass two dictionaries as an argument that returns the ChainMap instances to map the dictionaries the use of the dict() constructor to merge the dictionaries.

Let’s consider a software to merge two dictionaries the use of the ChainMap function in Python.

Chain_map.py

dict1 = {             
    'Student' : 'Butler',  
    'Course' : 'Computer Science',  
    'Address' : 'Los Angeles'  
}  
dict2 = {  
    'Teacher' : 'Rosy',  
    'Subject' : 'Computer Science'  
}  
from collections import ChainMap  # import the ChainMap from collections  
  
# Use ChainMap() constructor  
d3 = dict(ChainMap(dict1, dict2)) # passes two parameters as an argument  
  
print("Merge two dictionaries", d3) # Merge two dictionaries  

Output:

Merge two dictionaries {'Teacher': 'Rosy', 'Subject': 'Computer Science', 'Student': 'Butler', 'Course': 'Computer Science', 'Address': 'Los Angeles'}

Merge two dictionaries the usage of the itertools – chain() method

It makes an iterative dictionary that returns an issue from the first iterable dictionary till it is finished. And then, it proceeds to the subsequent iterable for further execution in a dictionary. Hence, it represents the consecutive sequences as a single sequence.

Syntax:

itertools.chain( *iterables )  

Let’s consider a software to merge two dictionaries using the chain feature in Python.

Chain.py

dict1 = {             
    'Student' : 'Butler',  
    'Course' : 'Computer Science',  
    'Address' : 'Los Angeles'  
}  
dict2 = {  
    'Teacher' : 'Rosy',  
    'Subject' : 'Computer Science'  
}  
from itertools import chain  # import the chain() function from itertools  
  
# Use ChainMap() constructor  
d3 = dict(chain(dict1.items(), dict2.items())) # passes two parameters as an argument  
  
print("Merge two dictionaries", d3) # Merge two dictionaries  

Output:

Merge two dictionaries {'Student': 'Butler', 'Course': 'Computer Science', 'Address': 'Los Angeles', 'Teacher': 'Rosy', 'Subject': 'Computer Science'}

Merge two dictionaries using the merge ( | ) operator

It is a merge (|) operator used to merge two dictionaries in Python. Python 3.9 has brought the merge ( | ) operator in the dict class.

Syntax:

dict1 |= dict2  

Let’s write a application to merge the two dictionaries in Python using the merge operator (|).

merge.py

def merge(dict1, dict):  
    result = dict1 | dict2 # use merge operator (|)  
    return result  
  
dict1 = {'A' : 'Apple', 'B' : 'Ball', 'C' : 'Cat' } # define dict1  
dict2 = {'D' : 'Dog', 'E' : 'Elephant', 'F' : 'Fish' } # define dict2  
dict3 = merge(dict1, dict2) # call merge() function  
print (dict3)    # print dict3  

Output:

{'A': 'Apple', 'B': 'Ball', 'C': 'Cat', 'D': 'Dog', 'E': 'Elephant', 'F': 'Fish'}