In this article, we will discuss the different ways to merge two dictionaries in Python. Python dictionary is an unordered collection of items. We will be using the below approaches to merge two dictionaries
- update() method
- copy() and update() method
- ** operator
- dict() constructor
- dict() with **kwargs
- Concatenation in dict()
- collections – ChainMap
- itertools – chain
Merge Two Dictionaries in Python
1. update() method
In this approach, we will be calling update() method, and this method updates the current dictionary with the content of the dictionary or any iterable of key/value pairs that are passed to it.
If we have two dictionaries like below
>>> d1 = {'Cricket':'Sachin', 'Football':'Zindane'} >>> d2 = {'Tennis' : 'Roger', 'Basketball' : 'Jordan'}
We can simply merge the two dictionaries bypassing d2 to the update() method
>>> d1.update(d2)
Now, d1 will have its original key/value pairs along with the content of d2.
>>> print(d1) {'Cricket': 'Sachin', 'Football': 'Zindane', 'Tennis': 'Roger', 'Basketball': 'Jordan'}
The important point to be noted here is we did not get a new dictionary. Instead, the key/value pairs of the dictionary d2 got appended with dictionary d1.
What if we needed a new dictionary? The solution is straightforward. We need to call the update() function on the newly created dictionary twice, like below.
>>> d3 = {} >>> d3.update(d1) >>> d3.update(d2) >>> d3 {'Cricket': 'Sachin', 'Football': 'Zindane', 'Tennis': 'Roger', 'Basketball': 'Jordan'}
What if we have the same key in both dictionaries?
>>> d1 = {'Cricket':'Sachin', 'Football':'Zindane'} >>> d2 = {'Tennis' : 'Roger', 'Cricket' : 'Lara'}
Let’s now try to merge both the dictionaries
>>> d1.update(d2)
>>> d1
{'Cricket': 'Lara', 'Football': 'Zindane', 'Tennis': 'Roger'}
As we have the same keys (Cricket) in both the dictionaries, while performing the update operation, the latest value overrides the old values.
Now when we print the d1 dictionary, we will be able to ‘Lara’ as the value instead of ‘Sachin’ for the key ‘Cricket.‘
2. copy() and update() method
In this approach, we will create a copy of the dictionary d1 using copy() function and assign it to a dictionary d3 and update the new dictionary d3 with the dictionary with d2 using update() function.
>>> d1 = {'Cricket':'Sachin', 'Football':'Zindane'} >>> d2 = {'Tennis' : 'Roger', 'Basketball' : 'Jordan'} >>> d3 = d1.copy() >>> d3 {'Cricket': 'Sachin', 'Football': 'Zindane'} >>> d3.update(d2) >>> d3 {'Cricket': 'Sachin', 'Football': 'Zindane', 'Tennis': 'Roger', 'Basketball': 'Jordan'}
This approach is slightly different from the previous approach, where we started with copying d1 to d3, followed by updating d3 with d2.
3. ** operator – Unpacking Operator
It is the most commonly used method to merge two dictionaries [Works with Python 3.5 or greater].
We all know that ** operator unpacks a dictionary, all we need to do is just unpack the dictionaries and merge them into a new dictionary.
>>> d1 = {'Cricket':'Sachin', 'Football':'Zindane'} >>> d2 = {'Tennis' : 'Roger', 'Basketball' : 'Jordan'} >>> d3 = {**d1, **d2} >>> d3 {'Cricket': 'Sachin', 'Football': 'Zindane', 'Tennis': 'Roger', 'Basketball': 'Jordan'}
We just unpacked both the dictionaries d1 and d2 using ** operator [Python kwargs] and merge them into a new dictionary d3.
In this approach, we can merge any number of dictionaries, say, for example, let’s merge the dictionaries d1, d2, d3 into a new dictionary d4.
>>> d1 = {'Cricket':'Sachin', 'Football':'Zindane'} >>> d2 = {'Tennis' : 'Roger', 'Basketball' : 'Jordan'} >>> d3 = {'Moto' : 'Rossi', 'Shuttle' : 'Sindhu'} >>> d4 = {**d1, **d2, **d3} >>> d4 {'Cricket': 'Sachin', 'Football': 'Zindane', 'Tennis': 'Roger', 'Basketball': 'Jordan', 'Moto': 'Rossi', 'Shuttle': 'Sindhu'}
Now dictionary d4 will have all the contents of dictionaries d1, d2, and d3.
4. dict() constructor
This approach is almost similar to the second approach, where we used a copy() and update() function, in this approach we will use the dict() constructor and followed by update() function call.
>>> d1 = {'Cricket':'Sachin', 'Football':'Zindane'} >>> d2 = {'Tennis' : 'Roger', 'Basketball' : 'Jordan'} >>> d3 = dict(d1) >>> d3.update(d2) >>> d3 {'Cricket': 'Sachin', 'Football': 'Zindane', 'Tennis': 'Roger', 'Basketball': 'Jordan'}
The dict() constructor creates a dictionary in Python, it can take **kwargs as a parameter, and since we have passed d1 as the parameter, it unpacks and adds the content to dictionary d3.
Now to merge the content of d2 with d3, by calling update() function and pass dictionary d2 to it.
5. dict() with **kwargs
This approach is kind of a shortcut to the above approach; in this approach, we will use a different dict() constructor, which can take a mapping and **kwargs.
>>> d1 = {'Cricket':'Sachin', 'Football':'Zindane'} >>> d2 = {'Tennis' : 'Roger', 'Basketball' : 'Jordan'} >>> d3 = dict(d1, **d2) >>> d3 {'Cricket': 'Sachin', 'Football': 'Zindane', 'Tennis': 'Roger', 'Basketball': 'Jordan'}
We just need to pass dictionary d1 and unpacked dictionary d2 using **kwargs to the dict() constructor. This creates a new dictionary d3 with the content of both d1 and d2.
6. Concatenation in dict()
In this approach, we will create a list of dictionary items and concatenate both the list and pass it to the dict() constructor.
>>> d1 = {'Cricket':'Sachin', 'Football':'Zindane'} >>> d2 = {'Tennis' : 'Roger', 'Basketball' : 'Jordan'} >>> d3 = (list(d1.items()) + list(d2.items())) >>> d3 [('Cricket', 'Sachin'), ('Football', 'Zindane'), ('Tennis', 'Roger'), ('Basketball', 'Jordan')]
The items() function returns the individual items present in the particular dictionary, For example
>>> d1.items() dict_items([('Cricket', 'Sachin'), ('Football', 'Zindane')])
List of items will create a list out of the items present
>>> list(d1.items()) [('Cricket', 'Sachin'), ('Football', 'Zindane')]
Now, all we need to do is just concatenate both the list and pass it to the dict() constructor.
Note: If you are using Python 2, then we can directly pass the dictionary items to the dict() constructor, an additional list is not required.
d3 = (d1.items() + d2.items()) # Works only in Python 2
7. collections – ChainMap
A ChainMap can group multiple dictionaries and return a single view out of it. This is often faster than creating a new dictionary and running multiple update() calls.
>>> d1 = {'Cricket':'Sachin', 'Football':'Zindane'}
>>> d2 = {'Tennis' : 'Roger', 'Basketball' : 'Jordan'}
>>> from collections import ChainMap
>>> d3 = dict(ChainMap(d1, d2))
>>> d3
{'Tennis': 'Roger', 'Basketball': 'Jordan', 'Cricket': 'Sachin', 'Football': 'Zindane'}
We need to import the ChainMap from the collections. ChainMap(d1, d2) returns the ChainMap instance, which is a dictionary-like mapping, we need to pass it to the dict() constructor to create a new dictionary.
8. itertools – chain
The chain() function takes up the *args parameter (*iterables). This function returns the element from each iterable so that it can be used to create a single sequence.
>>> d1 = {'Cricket':'Sachin', 'Football':'Zindane'}
>>> d2 = {'Tennis' : 'Roger', 'Basketball' : 'Jordan'}
>>> from itertools import chain
>>> d3 = dict(chain(d1.items(), d2.items()))
>>> d3
{'Cricket': 'Sachin', 'Football': 'Zindane', 'Tennis': 'Roger', 'Basketball': 'Jordan'}
We need to import the chain from the itertools, this returns the elements of both the dictionary d1 and d2. The returned elements can be passed to the dict() constructor to create a new dictionary.
Do let me know if you come across any new way to merge two Dictionaries in Python. Happy Learning!!
Leave a Reply