Register Login

Merge two Dictionaries in Python

Updated Jan 17, 2023

This tutorial will discuss how to merge two dictionaries in Python. In Python, Dictionary is one of the primary and most widely used data structures. If programmers wish to combine two dictionaries, they can use multiple methods to merge two or more dictionaries in Python.

It is usually not an unusual case where there is a need to combine or merge two dictionaries in Python.

What is a Dictionary in Python?

Dictionary is a commonly used data structure (an unordered collection of data elements) that includes all elements in key-value pairs in Python programming language. Each key-value pair corresponds to the keys with their corresponding value. Thus programmers can call it the associative array of Python Dictionary.

While declaring and initializing a dictionary, programmers need to put the dictionary's element within curly braces {}. Also, programmers use a colon (:) symbol to separate the key-value pairs from the adjacent (associative) values by placing them in between the key-value pairs.

In the next section of this article, we will learn how to merge two dictionaries using different methods of Python dictionaries.

What is known as merging in Python?

Merging is a technique of combining components of two or more elements into a single element. Programmers can merge the elements of two dictionaries into a single dictionary using the merge technique. There are various methods of Python dictionaries like the for loop, update() method, and others that merge a dictionary with items from other dictionaries.

  1. Using the update()
  2. Using For Loops
  3. Using the ** Operator
  4. Using dict() Constructor
  5. merge Operator

Method 1: Using the update() method to merge two dictionaries in Python:

The update() method in Python inserts a specified item into a new dictionary. In other words, the Python update() method updates the dictionary by adding the elements from a specified dictionary object or an iterable of key-value pairs.

Syntax:

dictionary.update(iterable)

Here, the parameter iterable specifies that programmers will insert the dictionary or an iterable object with key-value pairs into the existing dictionary.

Code Snippet:

def Merge(a, b):
	return(b.update(a))

# Define Dictionaries     
a = {'p': 90, 'q': 60}
b = {'r': 20, 's': 10}


print('Dictionary One: ', a)
print('Dictionary Two: ', b)
Merge(b, a)

print('Dictionary after merge: ', a)

Output:

Explanation:

The method merges the dictionary "b" with dictionary "a" and returns a new dictionary with the merged elements.

Method 2: Merging two dictionaries using For Loops:

The for loop is one of the most straightforward and widely used techniques. Programmers can use the for loops to merge two dictionaries by iterating the first dictionary and simultaneously adding access to the other dictionary to merge them.

Code Snippet:

Code Snippet:

first = { 'a' : 3234,      
            'b' : 345,  
            'c' : 2345,  
            'd' : 765  
                        }   
second = {  
            'p' : 765,     
            'q' : 3456,  
            'r' : 768  
}                          
print("The Dictionaries  look like this before we merge them:")  
print("The first Dictionary is : ", first)  
print("The second Dictionary is : ", second) 
demo = first.copy()  # Here, we copy the first into the demo using copy() method  
for key, value in second.items():  # Here, we use the for loop to iterate second into the demo dictionary  
    demo[key] = value  
print("After merging of the two Dictionary ")  
print(demo)    

 
Output:

Explanation:

In the above code snippet, we have used the for loop to iterate and merge two dictionaries in Python. First, the for loop will iterate over the dictionary and then merge the second dictionary with the first one.

Method 3: Using the ** in Python to merge two dictionaries:

Generally, when users use the ** operator, it becomes a trick where it uses a single expression to merge different dictionaries and stores it in a new Python dictionary.

Users can use the double star (**) that helps users pass multiple arguments to a function directly using the Python dictionary. ** or double star is the single expression and will not affect the other two dictionaries. The double star indicates that an argument is a dictionary.

Syntax:

{**Dictionary1, **Dictionary2}

Code Snippet:

def Merging(a, b):
	res = {**a, **b}
	return res

# Define Dictionaries 
a = {'p': 123, 'q': 654}
b = {'r': 987, 's': 456}

print('Dictionary One: ', a)
print('Dictionary Two: ', b)
demo = Merging(a, b)
print('Dictionary after merge: ', a)

Output:

Explanation:

First, programmers will pass all the items of the first dictionary into the third dictionary, using a double star (**), and then pass the second dictionary into the third. It will return the duplicate keys of the first dictionary. The double star will merge the items of the two dictionaries.

Method 4: Merge dictionaries using dict() constructor in Python:

The function of the dict() constructor method is the same as the copy() and update() in Python Dictionary. A dict() constructor copies the items of the first dictionary to a third dictionary and then follows the update() method to update the third dictionary with the items of the second dictionary.

Syntax:

second_dictionary.update(first_dictionary)

Code Snippet:

# Define Dictionaries 
first = { 'a' : 3234,      
            'b' : 345,  
            'c' : 2345,  
            'd' : 765  
}   
second = {  
            'p' : 765,     
            'q' : 3456,  
            'r' : 768  
}
print('Dictionary One: ', first)
print('Dictionary Two: ', second)

# Here, we use the dict() constructor  
demo = dict(first)  

demo.update(second)  
print("After we merge the two dictionaries", demo)

Output:

Explanation:

Here, we used the dict() constructor that helps to merge the items of two dictionaries into a new dictionary in Python.

Method 5: Using the merge operator to merge two dictionaries in Python:

This section of the article will discuss how to merge two dictionaries using the merge operator (|) in Python. Python 3.9 presented this merge ( | ) operator in a dict class. This operator joins two Python dictionaries into a single line of code.

Syntax:

first_dictionary |= second_dictionary

Code Snippet:

# Define Dictionaries 
first_dictionary  = { 'a' : 3234,
            'b' : 345,
            'c' : 2345,
            'd' : 765
}
second_dictionary  = {
            'p' : 765,
            'q' : 3456,
            'r' : 768
}

print('Dictionary One: ', first_dictionary)
print('Dictionary Two: ', second_dictionary)

demo = first_dictionary | second_dictionary;
print("After we merge the two dictionaries", demo)

Output:

Conclusion:

This article is all about merging dictionaries using various methods. In Python, The merging technique of two different data structures is one of the most commonly used and easy methods.

We have discussed four methods that allow users to combine and insert elements of two dictionaries into a single dictionary. These methods are as follows: using the update() method, ** (double star operator), for loop, dict() constructor, and merge operator in Python.


×