In Python, a dictionary is a data structure that contains the element in the key-value pair in which keys are used to access the values in the dictionary. Python has some inbuilt dictionaries like defaultdict. In this article, we will see various ways to merge two dictionaries.
Example
Input: dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}
Output: {'a': 10, 'b': 8, 'd': 6, 'c': 4}
Merging Two Dictionaries in Python
There are various ways in which Dictionaries can be merged by using various functions and constructors in Python. Below are some following ways:
Python update()
By using the method update() in Python, one list can be merged into another. But in this, the second list is merged into the first list and no new list is created. It returns None. In this example, we are using the update function to merge two dictionaries.
Python3
def Merge(dict1, dict2):
return (dict2.update(dict1))
dict1 = { 'a' : 10 , 'b' : 8 }
dict2 = { 'd' : 6 , 'c' : 4 }
print (Merge(dict1, dict2))
print (dict2)
|
Output:
None
{'c': 4, 'a': 10, 'b': 8, 'd': 6}
Time complexity: O(1)
Auxiliary space: O(1)
Python unpacking operator
Using ** [double star] is a shortcut that allows you to pass multiple arguments to a function directly using a dictionary. For more information refer **kwargs in Python. Using this we first pass all the elements of the first dictionary into the third one and then pass the second dictionary into the third. This will replace the duplicate keys of the first dictionary.
Python3
def Merge(dict1, dict2):
res = { * * dict1, * * dict2}
return res
dict1 = { 'a' : 10 , 'b' : 8 }
dict2 = { 'd' : 6 , 'c' : 4 }
dict3 = Merge(dict1, dict2)
print (dict3)
|
Output
{'a': 10, 'b': 8, 'd': 6, 'c': 4}
Time complexity: O(1)
Auxiliary complexity: O(n)
Python Merge Dictionaries Using | in Python 3.9
In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries. In this example, we are using | operator to merge two dictionaries.
Python3
def Merge(dict1, dict2):
res = dict1 | dict2
return res
dict1 = { 'x' : 10 , 'y' : 8 }
dict2 = { 'a' : 6 , 'b' : 4 }
dict3 = Merge(dict1, dict2)
print (dict3)
|
Output:
{'x': 10, 'a': 6, 'b': 4, 'y': 8}
Time complexity: O(1)
Auxiliary space: O(N)
Using for loop and keys() method
In this example, we are using loop and key() method to merge two dictionaries.
Python3
def Merge(dict1, dict2):
for i in dict2.keys():
dict1[i] = dict2[i]
return dict1
dict1 = { 'x' : 10 , 'y' : 8 }
dict2 = { 'a' : 6 , 'b' : 4 }
dict3 = Merge(dict1, dict2)
print (dict3)
|
Output
{'x': 10, 'y': 8, 'a': 6, 'b': 4}
Python Merge Dictionaries Using ChainMap Class
In this example, we are merging dictionaries in Python by using the built-in ChainMap class from the collections module. This class allows you to create a single view of multiple dictionaries, and any updates or changes made to the ChainMap will be reflected in the underlying dictionaries.
Python3
from collections import ChainMap
dict1 = { 'a' : 1 , 'b' : 2 }
dict2 = { 'c' : 3 , 'd' : 4 }
merged_dict = ChainMap(dict1, dict2)
print (merged_dict[ 'a' ])
print (merged_dict[ 'c' ])
merged_dict[ 'c' ] = 5
print (merged_dict[ 'c' ])
merged_dict[ 'e' ] = 6
print (merged_dict[ 'e' ])
|
Merge Two Dictionaries in Python Using dict constructor:
In this example, we are using dict constructor to merge two dictionaries.
Python3
def merge_dictionaries(dict1, dict2):
merged_dict = dict1.copy()
merged_dict.update(dict2)
return merged_dict
dict1 = { 'x' : 10 , 'y' : 8 }
dict2 = { 'a' : 6 , 'b' : 4 }
print (merge_dictionaries(dict1, dict2))
|
Output
{'x': 10, 'y': 8, 'a': 6, 'b': 4}
Time Complexity: O(N)
Auxiliary Space: O(N)
Python Merge Dictionaries Using dict() constructor and union operator (|)
This method uses the dict() constructor with the union operator (|) to merge two dictionaries. The union operator combines the keys and values of the two dictionaries, and any common keys in the two dictionaries take the value from the second dictionary.
Python3
def Merge(dict1, dict2):
merged_dict = dict (dict1.items() | dict2.items())
return merged_dict
dict1 = { 'a' : 10 , 'b' : 8 }
dict2 = { 'd' : 6 , 'c' : 4 }
merged_dict = Merge(dict1, dict2)
print (merged_dict)
|
Output
{'d': 6, 'b': 8, 'c': 4, 'a': 10}
Time complexity: O(n), where n is the total number of key-value pairs in both dictionaries.
Auxiliary Space: O(n), where n is the total number of key-value pairs in both dictionaries
Python Merge Two Dictionaries Using reduce():
In this example, we are merging two dictionaries using reduce() function. In this method, we define a merge function then takes two dictionaries as arguments and returns their merge.
Python3
from functools import reduce
def merge_dictionaries(dict1, dict2):
merged_dict = dict1.copy()
merged_dict.update(dict2)
return merged_dict
dict1 = { 'a' : 10 , 'b' : 8 }
dict2 = { 'd' : 6 , 'c' : 4 }
dict_list = [dict1, dict2]
result_dict = reduce (merge_dictionaries, dict_list)
print (result_dict)
|
Output
{'a': 10, 'b': 8, 'd': 6, 'c': 4}
Time complexity :O(n), where n is the number of dictionaries in the dict_list list.
Auxiliary complexity : O(m), where m is the total number of key-value pairs in all the dictionaries.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
15 Nov, 2023
Like Article
Save Article