In Python, dictionaries are mutable. This means that we can change the values of a dictionary after declaration.
This tutorial will teach you various ways of ‘concatenating’ two dictionaries into one.
Using the Pipe Operator
In Python 3 and above, you can use the pipe (|) operator to concatenate two dictionaries into 1.
An example is shown below:
other = {'Redis': 6379, 'MongoDB': 27017}
all = relational | other
print(all)
The code above should append the second dictionary to the first one in order of appearance.
This should result in a new dictionary as shown:
Using a for loop
We can also append two dictionaries using a for loop. It works by iterating over each key and value of one dictionary and appending it to the other.
An example is shown below:
other = {'Redis': 6379, 'MongoDB': 27017}
all = relational.copy() # copy the array
for k, v in other.items():
all[k] = v
print(all)
In the example above, we start by copying the first dictionary into the dictionary we wish to append. We then loop over each key and value of the second dictionary using the items() method.
Finally, we append the key and value to the copied dictionary.
The resulting output is as shown:
Using the ** Operator
The **kwargs operator in Python allows us to pass any number of arguments to a function. Hence, we can use this trick to unpack dictionaries into a new dict.
An example is illustrated below:
other = {'Redis': 6379, 'MongoDB': 27017}
all = {**relational, **other}
print(all)
The code above should return:
Using the Update Method
We can also use the update() method in Python dictionaries to merge two or more dictionaries.
An example usage is shown below:
other = {'Redis': 6379, 'MongoDB': 27017}
all = relational.copy()
all.update(other)
print(all)
In the example above, we start by copying the first dictionary. This helps us prevent overwriting the first dictionary.
Using ChainMap Method
We can also use the ChainMap method from the collections module to merge two dictionaries.
The ChainMap function allows us to group two or more dictionaries into a single updatable view.
An example is as shown:
all = ChainMap(relational, other)
print(all)
The ChainMap should take the dictionaries as the parameters and returns a merged dictionary as shown:
Note that the resulting type is not a native Python dictionary but a class.collections.ChainMap type.
Conclusion
In this article, we dove deep into various methods of merging two or more dictionaries in Python.