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.
Python
# Python code to merge dict using update() method
def Merge(dict1, dict2):
return(dict2.update(dict1))
# Driver code
dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}
# This returns None
print(Merge(dict1, dict2))
# changes made in dict2
print(dict2)
Output:
None
{'c': 4, 'a': 10, 'b': 8, 'd': 6}
Time complexity: O(n)
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.
Python
# Python code to merge dict using a single
# expression
def Merge(dict1, dict2):
res = {**dict1, **dict2}
return res
# Driver code
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.
Python
# code
# Python code to merge dict using a single
# expression
def Merge(dict1, dict2):
res = dict1 | dict2
return res
# Driver code
dict1 = {'x': 10, 'y': 8}
dict2 = {'a': 6, 'b': 4}
dict3 = Merge(dict1, dict2)
print(dict3)
# This code is contributed by virentanti16
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.
Python
# code
# Python code to merge dictionary
def Merge(dict1, dict2):
for i in dict2.keys():
dict1[i]=dict2[i]
return dict1
# Driver code
dict1 = {'x': 10, 'y': 8}
dict2 = {'a': 6, 'b': 4}
dict3 = Merge(dict1, dict2)
print(dict3)
# This code is contributed by Bhavya Koganti
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.
Python
from collections import ChainMap
# create the dictionaries to be merged
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
# create a ChainMap with the dictionaries as elements
merged_dict = ChainMap(dict1, dict2)
# access and modify elements in the merged dictionary
print(merged_dict['a']) # prints 1
print(merged_dict['c']) # prints 3
merged_dict['c'] = 5 # updates value in dict2
print(merged_dict['c']) # prints 5
# add a new key-value pair to the merged dictionary
merged_dict['e'] = 6 # updates dict1
print(merged_dict['e']) # prints 6
Merge Two Dictionaries in Python Using dict constructor:
In this example, we are using dict constructor to merge two dictionaries.
Python
def merge_dictionaries(dict1, dict2):
merged_dict = dict1.copy()
merged_dict.update(dict2)
return merged_dict
# Driver code
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.
Python
# method to merge two dictionaries using the dict() constructor with the union operator (|)
def Merge(dict1, dict2):
# create a new dictionary by merging the items of the two dictionaries using the union operator (|)
merged_dict = dict(dict1.items() | dict2.items())
# return the merged dictionary
return merged_dict
# Driver code
dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}
# merge the two dictionaries using the Merge() function
merged_dict = Merge(dict1, dict2)
# print the merged dictionary
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.
Python
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] # Put the dictionaries into a list
result_dict = reduce(merge_dictionaries, dict_list)
print(result_dict)
#This code is contributed by Rayudu.
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.
Python | Merging two Dictionaries – FAQs
Which statement is used to merge two dictionaries in Python?
To merge two dictionaries in Python, you can use the update() method or the ** unpacking operator (in Python 3.5 and later).
Using update() method:
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
print(dict1) # Output: {'a': 1, 'b': 3, 'c': 4}
Using the ** unpacking operator:
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict) # Output: {'a': 1, 'b': 3, 'c': 4}
How to join dictionary values in Python?
To join dictionary values into a single string, you can use the join() method after converting the values to strings.
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Join values into a single string
joined_values = ''.join(str(value) for value in my_dict.values())
print(joined_values) # Output: '123'
How to merge two dictionaries in Python with overwrite?
When merging two dictionaries using the update() method or the ** unpacking operator, the values from the second dictionary will overwrite those in the first dictionary for matching keys.
Using update() method:
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
print(dict1) # Output: {'a': 1, 'b': 3, 'c': 4}
Using the ** unpacking operator:
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict) # Output: {'a': 1, 'b': 3, 'c': 4}
How to combine two lists of dictionaries?
To combine two lists of dictionaries, you can use the + operator to concatenate them.
list1 = [{'a': 1}, {'b': 2}]
list2 = [{'c': 3}, {'d': 4}]
combined_list = list1 + list2
print(combined_list) # Output: [{'a': 1}, {'b': 2}, {'c': 3}, {'d': 4}]
Please Login to comment...