How to merge two Python dictionaries into single expression?
In Python, Dictionaries are very powerful data structure as it stores the data as a key value pair. While working on dictionaries we may need to merge two dictionaries to obtain the resultant dictionary. There are two different scenarios to perform this task. First one is by overwriting the content of original dictionary and the other one is by storing the result of merging in new dictionary. Using second scenario, the content of original dictionary will not be modified. Depending upon the requirement of application, appropriate functions can be used to achieve this task.
There are six different ways to merge two python dict into single expression.
- Using update function
- Using copy and update function
- Using keyword argument syntax(**)
- Using Lambda function
- Using
itertools.chain()
method - Using | (OR) operator
Method-1: Using update function
This is a simplest approach to merge two python dictionaries. This approach is used only if we don't mind overwriting the content of original dictionaries. Here, we will use update method so that all the content from dictionary d2 will be appended to d1 for all the unique keys. However, if both the dictionaries have some keys in common, it will overwrite the existing value with the new value.
Example
# Initializing dictionaries
d1={'fruit': 'Apple', 'calories': 100}
d2={'vegetable': 'Tomato', 'calories': 50}
print("d1: ", d1)
print("d2: ", d2)
# Using update function to merge two python dictionaries
d1.update(d2)
print("Resultant merged Dictionary: ", d1)
Output
d1: {'fruit': 'Apple', 'calories': 100}
d2: {'vegetable': 'Tomato', 'calories': 50}
Resultant merged Dictionary: {'fruit': 'Apple', 'calories': 50, 'vegetable': 'Tomato'}
Method-2: Using copy and update function
This is a traditional approach to merge two python dictionaries without modifying the content of original dictionaries. This approach was used in all the applications that uses python version 3.4 or lower. Here, we will store a shallow copy of the dictionary d1 in merge. Thereafter, we will merge the content using update method for dictionary d2. Finally, this merged dictionary will be returned to a calling function. Note that the original content of dictionaries will not be modified.
Example
# Function to merge two python dictionaries
def merge_dicts(a, b):
# Creating a copy of d1 and storing it in merge
merge = a.copy()
# merging contents of merge and d2
merge.update(b)
# returning the merged dictionary
return merge
# Initializing dictionaries
d1={'fruit': 'Apple', 'calories': 100}
d2={'vegetable': 'Tomato', 'calories': 50}
print("d1: ", d1)
print("d2: ", d2)
# Calling function
result = merge_dicts(d1, d2)
print("Resultant merged Dictionary: ", result)
Output
d1: {'fruit': 'Apple', 'calories': 100}
d2: {'vegetable': 'Tomato', 'calories': 50}
Resultant merged Dictionary: {'fruit': 'Apple', 'calories': 50, 'vegetable': 'Tomato'}
Method-3: Using keyword argument syntax(**)
In Python 3.5 and above we can use the keyword argument syntax (**kwargs) to merge two dictionaries in a single expression. We can merge all the elements from d1 and d2 in a third dictionary d3 without altering the elements of original dictionaries. Note that here, in order to merge the content of dictionary, both the dictionary should have unique keys. Otherwise, it will overwrite the values of first occurrence of key with the second occurrence of same key.
Example 1
# Initializing dictionaries
d1 = {'name': 'Ram', 'employeeid': 2254}
d2 = {'city': 'Pune', 'state': 'Maharashtra'}
print("Dictionary d1: ", d1)
print("Dictionary d2: ", d2)
# using ** syntax to pass and store contents of d1 and d2 in z
z = {**d1, **d2}
print("Resultant merged Dictionary: ", z)
Output
Dictionary d1: {'name': 'Ram', 'employeeid': 2254}
Dictionary d2: {'city': 'Pune', 'state': 'Maharashtra'}
Resultant merged Dictionary: {'name': 'Ram', 'employeeid': 2254, 'city': 'Pune', 'state': 'Maharashtra'}
Method-4: Using Lambda function
In this approach, we will use lambda function to merge two python dictionaries. This lambda function will be evaluated as a single expression. Here, firstly we will copy the dictionary d1 in l. Thereafter, we will update l by merging it with dictionary d2 and then returning the value of l as a merged dictionary. Note that the original content of dictionaries will not be modified.
Example
# Initializing the dictionaries
d1 = {'fruit': 'Apple', 'calories': 100}
d2 = {'vegetable': 'Tomato', 'calories': 50}
print("d1: ", d1)
print("d2: ", d2)
# Using lambda function first copies d1 in l, it will then update l by merging it with d2
merge = (lambda l=d1.copy(): (l.update(d2), l)[1])()
print("Resultant merged Dictionary: ", merge)
Output
d1: {'fruit': 'Apple', 'calories': 100}
d2: {'vegetable': 'Tomato', 'calories': 50}
Resultant merged Dictionary: {'fruit': 'Apple', 'calories': 50, 'vegetable': 'Tomato'}
Method-5: Using itertools.chain() method
The itertools module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. The chain()
method of itertools is used to accept a series of iterable and it then returns a single iterable. So, we can create a chain of dictionaries and store the result in the merge dictionary. Note that the content of the original dictionaries will not be modified.
Example
# Import chain module
from itertools import chain
# Initializing the dictionaries
d1={'fruit': 'Apple', 'calories': 100}
d2={'vegetable': 'Tomato', 'calories': 50}
print("d1: ", d1)
print("d2: ", d2)
# Using chain to merge two python dictionaries
result = dict(chain(d1.items(),d2.items()))
print("Resultant merged Dictionary: ", result)
Output
d1: {'fruit': 'Apple', 'calories': 100}
d2: {'vegetable': 'Tomato', 'calories': 50}
Resultant merged Dictionary: {'fruit': 'Apple', 'calories': 50, 'vegetable': 'Tomato'}
Method-6: Using |(OR) operator to merge two python dictionaries
This approach will only work for Python 3.9 or higher versions. Here, we are using | (Or) operator to merge the content of two python dictionaries. Note that the content of the original dictionaries will not be modified. Also, the resultant dictionary will hold unique keys. So if two dictionaries have any key in common, it's value will be overwritten by the second one.
Example
# Initializing the dictionaries
d1={'fruit': 'Apple', 'calories': 100}
d2={'vegetable': 'Tomato', 'calories': 50}
print("d1: ", d1)
print("d2: ", d2)
# Using OR operator to merge two python dictionaries
result = d1 | d2
print("Resultant merged Dictionary: ", result)
Output
d1: {'fruit': 'Apple', 'calories': 100}
d2: {'vegetable': 'Tomato', 'calories': 50}
Resultant merged Dictionary: {'fruit': 'Apple', 'calories': 50, 'vegetable': 'Tomato'}
Summary
The knowledge of merging two python dictionaries is very important while working on real time applications. Dictionaries are powerful data structure in Python. Many times we will need to merge the content of two dictionaries in order to show it in the results. In this tutorial, we covered the five different ways to merge two python dictionaries with an example. All in all, this tutorial, covers everything that you need to know in order to merge two python dictionaries.
References
Python Dictionary
itertools module