Python dictionary is an unordered collection of items. While other compound data types have only values as an element, dictionary has a key: value pair. While working with data, it is common to merge dictionary into one.
There are two ways to merge two or more dictionaries in Python:
- Merging dictionaries using dict.update().
- Merging using **kwargs.
Merge two or more dictionaries using dict.update()
Python Dictionary update() is a built-in function that accepts another dictionary or an iterable object (collection of key-value pairs) as an argument. The update() method doesn’t create a new dictionary; it changes the content of the existing dictionary. Following code shows merging of two dictionary using example.
# Create dictionaries
x = {'a': 11, 'b': 21}
y = {'b': 32, 'c':4}
# Merge contents of x in y
x.update(y)
print('Updated dictionary is :')
print(x)
#Output
Updated dictionary is :
{'a': 11, 'b': 32, 'c': 4}
In case of duplicate key, update method overwrites old values of the dictionary with the new values of the updating dictionary. So as shown in the above example, that value of key ‘b’ is overwritten to 32 from 11.
Merge two or more Dictionaries using **kwargs
The **
operator is used to return the data elements stored in an iterator one by one. We can use this operator to form one dictionary object using two dictionaries. It doesn’t work with version 3.4 or lower.
Applying ** to the dictionary, de-serializes the contents of the dictionary to a collection of key-value pairs.
#Creating dictionaries
x = {'a': 11, 'b': 21}
y = {'b': 32, 'c': 4}
z = {**x, **y}
print("Merged Dictionary: ")
print(z)
#Output
Merged Dictionary:
{'a': 11, 'b': 32, 'c': 4}
The **x and **y expanded the contents of both the dictionaries to a collection of key-value pairs. Then {} puts it into a new dictionary.
C P Gupta is a YouTuber and Blogger. He is expert in Microsoft Word, Excel and PowerPoint. His YouTube channel @pickupbrain is very popular and has crossed 9.9 Million Views.