The Python Dictionary is a data structure that stores all elements as key-value pairs. Each key-value pair associates the keys with their corresponding associative value. Python dictionaries are unordered and changeable, which means that their elements can be altered. However, by concatenating two or more dictionaries, a new dictionary can be produced. In Python, it’s not uncommon to want to merge two dictionaries. In this post, we will look at a few methods for combining dictionaries.
Merging Dictionaries
Dictionary merges are typically performed from right to left, as dict a <- dict b.
But what if both the dictionaries contain a similar key? In such situations, When a common key holder exists in both the dictionaries, always, the value of the second dictionary overwrites the value of the first.
Example 1: Using the | Operator
In Python, it is a merge (|) operator that is used to join two dictionaries in a single line of code. In Python 3.9, the merge ( | ) operator was added to the dict class.
Example
dict1 = {1: 'One', 2: 'Two', 3: 'Three'}
dict2 = {3: 'Zero', 4: 'Four'}
print('Merged dictionary:', dict1|dict2)
Output
Merged dictionary: {1: 'One', 2: 'Two', 3: 'Zero', 4: 'Four'}
Note – If two keys with the same name exist, the value of the latter key is included in the merged dictionary.
Example 2: Using the ** Operator
For earlier versions of Python 3, we can combine by unpacking both dictionaries inside another dictionary, using the ** double asterisks. The Unpacking Operator (**) is used for this. The ** denotes that an argument is a dictionary. ** [double star] is a shortcut that allows you to use a dictionary to pass multiple arguments to a function. We can also combine multiple dictionaries using this method.
Example
dict1 = {1: 'John', 2: 'Sam', 3: 'Tim'}
dict2 = {3: 'Kim', 4: 'Kelly'}
# Using the unpacking operator
res = {**dict1, **dict2}
print('Merged dictionary:', res)
Output
Merged dictionary: {1: 'John', 2: 'Sam', 3: 'Kim', 4: 'Kelly'}
Example 3: Using copy() and update()
Dictionary has an update() method that merges the dictionary in place with the contents from the other dictionary and overwrites existing keys. One list can be merged into another using Python’s update() technique. However, the second list is merged into the first list in this technique, and no new list is generated. It returns a value of None.
Example
dict1 = {1: 'John', 2: 'Sam', 3: 'Tim'}
dict2 = {3: 'Kim', 4: 'Kelly'}
# Using copy() and update()
dict3 = dict2.copy()
dict3.update(dict1)
print('Merged dictionary:', dict3)
Output
Merged dictionary: {3: 'Tim', 4: 'Kelly', 1: 'John', 2: 'Sam'}
Using the dictionary copy() method, we first transferred the elements of dict2 to dict3. The dictionary update() method was then used to update dict3 with the values of dict1.
Example 4: Using collections.ChainMap
This is possibly the least known method of combining dictionaries. The collections module’s ChainMap class organizes many dictionaries into a single view. This function returns a ChainMap class object. We continue to use this object in the same way that we would any other dictionary.
Note – The only distinction is that if two dictionaries contain the same keys, this method will return the value from the first dictionary, as opposed to the other methods, which return the value from the second dictionary.
Example
from collections import ChainMap
dict1 = {1: 'John', 2: 'Sam', 3: 'Tim'}
dict2 = {3: 'Kim', 4: 'Kelly'}
# Using ChainMap()
dict3 = ChainMap(dict1, dict2)
print('Merged dictionary:', dict3)
Output
Merged dictionary: ChainMap({1: 'John', 2: 'Sam', 3: 'Tim'}, {3: 'Kim', 4: 'Kelly'})
Example 5: Unpacking the second dictionary
By unpacking the second dictionary, we may combine the dictionaries. This approach, however, is only applicable if the keys in the second dictionary are strings.
Example
dict1 = {1: 'John', 2: 'Sam', 3: 'Tim'}
dict2 = {'3': 'Kim', '4': 'Kelly'}
dict3 = dict(dict1, **dict2)
print('Merged dictionary:', dict3)
Output
Merged dictionary: {1: 'John', 2: 'Sam', 3: 'Tim', '3': 'Kim', '4': 'Kelly'}
Leave a Reply