Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are Python dictionaries?
3.
Methods to merge two dictionaries in python
3.1.
1. Using the merge ‘|’ operator
3.2.
2. Using ** operator
3.3.
3. Using update method
3.4.
4. Using copy and update method
3.5.
5. Using dict() constructor
3.6.
6. Using for loop
3.7.
7. Using Collections
4.
Frequently Asked Questions
4.1.
In Python, can you append a dictionary to another dictionary?
4.2.
In Python, what does keys() do?
4.3.
How can we create a dictionary in Python? 
5.
Conclusion
Last Updated: Sep 30, 2024
Medium

How to merge two dictionaries in python?

Author Ashish Sharma
0 upvote

Introduction

A dictionary is a data collection that can be changed and ordered. It does not allow duplicates. Dictionary in python stores data values in key: value pairs. Dictionaries are ordered from python version 3.7. 

In this article, we will learn about python dictionaries, how to merge python dictionaries, examples, and their implementations.

What are Python dictionaries?

Dictionaries are the fundamental data structures in Python. It can hold an arbitrary number of objects identified by a distinct dictionary key. Python dictionaries are ordered and mutable. To learn more about python dictionaries, refer to the link.

Methods to merge two dictionaries in python

There are various methods by which we can merge two dictionaries in python. These methods are mentioned in the below image.

Methods to merge two dictionaries in python
  1. Using merge ‘|’ operator
  2. Using ** operator
  3. Using update method
  4. Using copy and update method
  5. Using dict() constructor
  6. Using for loop
  7. Using Collections

Let us now discuss each method in detail.

1. Using the merge ‘|’ operator

‘|’ operator is used to merge two dictionaries that have different data into one. We will discuss its syntax and implementation here.

Syntax: dictionary1|=dictionary2

Example

def Merge(dictionary1, dictionary2):
for i in dictionary2.keys():
dictionary1[i]=dictionary2[i]
return dictionary1

dictionary1 = {'Name': 'Ashish', 'Company': 'Coding ninjas'}
dictionary2 = {'Course': 'CSE', 'Subject': 'merge two dictionaries in python'}
print(dict(dictionary1.items() | dictionary2.items()))
You can also try this code with Online Python Compiler
Run Code

Output

{'Name': 'Ashish', 'Company': 'Coding ninjas', 'Course': 'CSE', 'Subject': 'merge two dictionaries in python'}

2. Using ** operator

The ** operator is used to combine two or more dictionaries with a single expression.

Syntax: dict(**data_1)

Example 1

dictionary_1 = {'Ashish': 21, 'Swati': 20, 'pranav': 22}
print(dict(**dictionary_1))
You can also try this code with Online Python Compiler
Run Code

Output

{'Ashish': 21, 'Swati': 20, 'pranav': 22}

Example 2

dictionary1 = {'Coding ninjas ' : 'Ashish',       
    'Amazon' : 'Swati',  
    'Microsoft': 'Amit',  
    }  
dictionary2 = {'Operating system ' : 'Windows',  
    'database' : 'MySQL',  
'Microsoft': 'Ashish',  
    }  
dictionary3 = {'Ashish': 21, 'Swati': 20, 'pranav': 22}

dictionary4 = {  
    **dictionary1, **dictionary2 ,**dictionary3  
    } 
print(dict(**dictionary4))
You can also try this code with Online Python Compiler
Run Code

Output

{'Coding ninjas ': 'Ashish', 'Amazon': 'Swati', 'Microsoft': 'Ashish', 'Operating system ': 'Windows', 'database': 'MySQL', 'Ashish': 21, 'Swati': 20, 'pranav': 22}

Here we are merging more than two dictionaries and printing as one.

3. Using update method

It is used to update the current data with other data and print them as one.

Example

dictionary1 = {'Coding ninjas ' : 'Ashish',       
    'Amazon': 'Swati',  
    'Microsoft': 'Amit',  
    }  
  
dictionary2 = {'Operating system ' : 'Windows',  
    'database' : 'MySQL',  
'Microsoft': 'Ashish',  
    }  
  
dictionary1.update(dictionary2) 
# appending the dictionary2 dictionary items into the dictionary1 dictionary.  
print( "Merging two dictionaries :")  
print(dictionary1)
# print the merge dictionary   
You can also try this code with Online Python Compiler
Run Code

Output

Merging two dictionaries :
{'Coding ninjas ': 'Ashish', 'Amazon': 'Swati', 'Microsoft': 'Ashish', 'Operating system ': 'Windows', 'database': 'MySQL'}

You can practice by yourself with the help of online python compiler for better understanding.

In the above example,  we have taken two same data in different dictionaries. Still, it takes the data of dictionary 2 as dictionary 1 is updating the values of dictionary 2 with its own values.

4. Using copy and update method

In this method, we will first copy the data from dictionary 1 to dictionary 3, and then we will update dictionary 3 with the data of dictionary 1. We will understand it with easy implementation.

Syntax: dictionary_1=dictionary2_copy()

dictionary_3.update(dictionary_1)

Example

dictionary_1 = {1: 'Ashish', 2: 'Amit'}
dictionary_2 = {2: 'Pranav', 4: 'Aditi'}

dictionary_3 = dictionary_2.copy()
dictionary_3.update(dictionary_1)

print(dictionary_3)
You can also try this code with Online Python Compiler
Run Code

Output

{2: 'Amit', 4: 'Aditi', 1: 'Ashish'}

Here you can see that we have copied the data from dicrionary_2 to dictionary_3 using the copy() method, and then we have updated the dictionary_3 with dictionary_1.

5. Using dict() constructor

A dict() constructor copy the first dictionary elements with the new dictionary and then follow an update() method to update all the new dictionary by a second dictionary's element.

Example 1

dictionary1 = {             
    'Student' : 'Ashish',  
    'Course' : 'Merge two dictionaries in python',  
    'Address' : 'Delhi'  
}  
  
dictionary2 = {  
    'Teacher' : 'Ashta',  
    'Subject' : 'CSE'  
}  
  
# Use dict() constructor  
dictionary3 = dict(dictionary1)  
print("Elements before merging the data",dictionary3);
# print("Before Merge", dictionary3)  
dictionary3.update(dictionary2)  
print("Merge two dictionaries", dictionary3) # Merge two dictionaries   
You can also try this code with Online Python Compiler
Run Code

Output

Elements before merging the data {'Student': 'Ashish', 'Course': 'Merge two dictionaries in python', 'Address': 'Delhi'}
Merge two dictionaries {'Student': 'Ashish', 'Course': 'Merge two dictionaries in python', 'Address': 'Delhi', 'Teacher': 'Ashta', 'Subject': 'CSE'}

Example 2

Here we will use dict() constructor and ** operator both to merge two dictionaries in python.

Syntax: Dictionary3 =dict(dictionary1,**dictionary2)


dictionary1 = {             
    'Student' : 'Ashish',  
    'Course' : 'Merge two dictionaries in python',  
    'Address' : 'Delhi'  
}  
  
dictionary2 = {  
    'Teacher' : 'Ashta',  
    'Subject' : 'CSE' ,
    'chapter':'merge two dictionaries in python'
}  
  
# Use dict() constructor  
dictionary3 = dict(dictionary1)  
print("Elements before merging the data",dictionary3);
# print("Before Merge", dictionary3)  
dictionary3 = dict(dictionary1, **dictionary2)  
print("Merge two dictionaries", dictionary3) # Merge two dictionaries   
You can also try this code with Online Python Compiler
Run Code

Output

Elements before merging the data {'Student': 'Ashish', 'Course': 'Merge two dictionaries in python', 'Address': 'Delhi'}
Merge two dictionaries {'Student': 'Ashish', 'Course': 'Merge two dictionaries in python', 'Address': 'Delhi', 'Teacher': 'Ashta', 'Subject': 'CSE', 'chapter': 'merge two dictionaries in python'}

6. Using for loop

In this method, we will loop the elements to copy from one dictionary to another, and after that, we will update it.

 Example

Example:
# Python code to merge dictionary
def Merge(dictionary1, dictionary2):
for i in dictionary2.keys():
dictionary1[i]=dictionary2[i]
return dictionary1

# Driver code
dictionary1 = {'Name': 'Ashish', 'Company': 'Coding ninjas'}
dictionary2 = {'Course': 'CSE', 'Subject': 'merge two dictionaries in python'}
dictionary3 = Merge(dictionary1, dictionary2)
print(dictionary3)
You can also try this code with Online Python Compiler
Run Code

Output

{'Name': 'Ashish', 'Company': 'Coding ninjas', 'Course': 'CSE', 'Subject': 'merge two dictionaries in python'}

7. Using Collections

ChainMap is a set of dictionaries that returns a single dictionary. When we compare it to the update () technique, it is faster to construct a new dictionary and run several files. We will import the ChainMap from collections to join the two dictionaries in Python.

Example:
In this example, we will see how we can use collections to merge dictionaries using the chain map() constructor.

def Merge(dictionary1, dictionary2):
	for i in dictionary2.keys():
		dictionary1[i]=dictionary2[i]
	return dictionary1
dictionary1 = {'Name': 'Ashish', 'Company': 'Coding ninjas'} 
# declaring the dictionary 1 elements

dictionary2 = {'Course': 'CSE', 'Subject': 'merge two dictionaries in python'} 
# declaring the dictionary 2 elements

from collections import ChainMap  # import the ChainMap from collections  
# Using ChainMap() constructor  

dictionary3 = dict(ChainMap(dictionary1, dictionary2))
# d3 = dict(ChainMap(dict1, dict2)) 
# passes two parameters as an argument  
print(dictionary3)
You can also try this code with Online Python Compiler
Run Code

Output

{'Course': 'CSE', 'Subject': 'merge two dictionaries in python', 'Name': 'Ashish', 'Company': 'Coding ninjas'}

Also see, How to Check Python Version in CMD

Frequently Asked Questions

In Python, can you append a dictionary to another dictionary?

Yes, the update() method is used to append a dictionary. The update() method connects one dictionary to another and involves inserting key-value pairs from one dictionary into another.

In Python, what does keys() do?

In Python Dictionary, the keys() method provides the view object, which displays a list of all the keys in the dictionary in order of insertion using Python. 

How can we create a dictionary in Python? 

We can create a dictionary in Python in two ways as follows:

Using curly braces ( { } ):
Dictionary1 = {“name”:”Ashish”, “age”:21 }
Using the dict( ) constructor:
Dictionary = dict(name=”Ashish”, age=21)

Conclusion

In this article, we have learned the Python dictionaries, how to merge Python dictionaries, examples, and their implementations.

After reading about merge two dictionaries in Python, are you not feeling excited to read/explore more articles on python? Don't worry; Coding Ninjas has you covered. If you want to check out Python-related articles, refer to the 

Also check out - Data Dictionary In Software Engineering
Refer to our Guided Path on Code360 to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! 
Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Live masterclass