How to Merge Two Dictionaries in Python

Python dictionary is a popular data structure that allows you to easily store a large amount of different data in a compact manner, as key-value pairs. They are commonly used by web developers since they can be directly converted to JSON and vice versa. Often, Python developers need to merge dictionaries in Python as part of software development. There are several ways to combine Python dictionaries. In this article, we will learn how to merge two dictionaries in Python.

How to Merge Two Dictionaries in Python

Here are the different ways to merge two dictionaries in Python. Before we proceed, it is important to understand that some of these solutions produce a new dictionary while others overwrite one of the two dictionaries. Also, if the dictionaries contain common keys, then the order of merge will decide the final values of duplicate keys. It is important to consider these factors before you choose a way to merge dictionaries.

Let us say we have the following 3 dictionaries – d1 and d2 that do not have any common keys whereas d1 and d3 have a common key ‘b’. Let us look at the different ways to merge two Python dictionaries.

d1 = {'a':1, 'b' : 2}
d2 = {'c':3, 'd' : 4}
d3 = {'b':5, 'e' : 6}

1. Using update()

You can use update() function to easily merge one dictionary into another. In this case, it will not result in a new dictionary but one of the dictionaries will be overwritten with the merged dictionary. Here is an example to merge d1 and d2.

d1 = {'a':1, 'b' : 2}
d2 = {'c':3, 'd' : 4}
d3 = {'b':5, 'e' : 6}

d1.update(d2)
print(d1) # output is {'a': 1, 'b': 2, 'c': 3, 'd': 4}

As you can see, the dictionary d1 has been updated. On the other hand, if you reverse d1 and d2 in above command, you will see that d2 has been updated.

d2.update(d1)
print(d2) # output is {'c': 3, 'd': 4, 'a': 1, 'b': 2}

In both the above cases, the merged dictionary is the same but different dictionary is overwritten. So the order of merge is important while using update() function.

In both the above examples, d1 and d2 do not have any common keys. Let us see what happens if there is a duplicate key in the two dictionaries, such as in case of d1 and d3.

d1.update(d3)
print(d1) # output is {'a': 1, 'b': 5, 'e': 6}

As you can see, the dictionary d1 has been updated. Also, the value of duplicate key ‘b’ is equal to its value in the 2nd dictionary d3. On the other hand, if you reverse d1 and d3 in above command, you will see that d3 has been updated.

d3.update(d1)
print(d3) # output is {'b': 2, 'e': 6, 'a': 1}

As you can see, the order of merge determines which dictionary is updated. In this case, the value of duplicate key ‘b’ is equal to its value in the 2nd dictionary d1.

Please note, once the dictionary is merged and updated, you will not be able to get back your original dictionary.

If you want to retain original dictionaries and save the merge dictionary separately, then you need to create a copy of one of the dictionaries and then use it with update() function as shown below.

d4 =d1.copy()
d4.update(d2)
print(d4) # output is {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print(d1) # output is {'a': 1, 'b': 2}

2. Using Unpacking operator

The unpacking operator ‘**’, also known as double star operator, is another easy way to quickly merge two or more dictionaries at one go. However, unlike update() function, this method results in a new dictionary and does not update any of the existing ones. Here is an example to merge dictionaries d1 and d2.

d1 = {'a':1, 'b' : 2}
d2 = {'c':3, 'd' : 4}
d3 = {'b':5, 'e' : 6}

d4 = {**d1, **d2}
print(d4) # output is {'a': 1, 'b': 2, 'c': 3, 'd': 4
print(d1) # output is {'a': 1, 'b': 2}
print(d2) # output is {'c': 3, 'd': 4}

In the above case, the dictionary d1’s items are first written to d4 and then dictionary d2’s items are written to it. If there are any duplicate keys, then the values of 1st dictionary are overwritten by those of the 2nd dictionary.

d4 = {**d1, **d3}
print(d4) # output is {'a': 1, 'b': 5, 'e': 6}

d4 = {**d3, **d1}
print(d4) # output is {'b': 2, 'e': 6, 'a': 1}

In the above 2 examples, d1 and d3 have a common key ‘b’. In first case, the the value of ‘b’ is equal to that in d3 whereas in the 2nd case it is equal to that in d1. So the order of merging is important in this case. In both the above cases, the duplicate keys present in first dictionary are replaced by those in second dictionary.

3. Using “|” operator

Starting Python 3.9, you can also use ‘I’ union operator to easily merge Python dictionaries. Its syntax is similar to concatenating string variables. It results in a new separate dictionary. Here is an example to merge dictionaries d1 and d2.

d1 = {'a':1, 'b' : 2}
d2 = {'c':3, 'd' : 4}
d3 = {'b':5, 'e' : 6}

d4 = d1 | d2
print(d4) # output is {'a': 1, 'b': 2, 'c': 3, 'd': 4}

If there are no duplicate keys, as shown above, then the order of dictionaries does not matter. Otherwise, it matters. Here is an example to merge dictionaries d1 and d3 which have duplicate key ‘b’.

d4 = d1 | d3
print(d4) # {'a': 1, 'b': 5, 'e': 6}
d4 = d3 | d1
print(d4) # {'b': 2, 'e': 6, 'a': 1}

In both the examples, the duplicate key of first dictionary is overwritten by that of the second dictionary. That is why you will see the result is different in both the cases. Therefore, the order of dictionary is important if you have duplicate keys.

4. Using Loop & Keys

This is the old fashioned way of looping through one dictionary and adding its key-value pairs to the other one. Here is an example to merge dictionaries d1 and d2 this way. We use keys() function to get a list of dictionary keys. Then we loop through them, and add those key-value pairs to the other dictionary.

d1 = {'a':1, 'b' : 2}
d2 = {'c':3, 'd' : 4}
d3 = {'b':5, 'e' : 6}

for i in d2.keys():
d1[i]=d2[i]
print(d1) # output is {'a': 1, 'b': 2, 'c': 3, 'd': 4}

In this case, you do not get a new dictionary but the items of d2 are added to d1. If you switch d1 and d2 in above code, then d2 is updated and d1 remains unchanged.

for i in d1.keys():
d2[i]=d1[i]
print(d2) # output is {'c': 3, 'd': 4, 'a': 1, 'b': 2}

So as you can see, the order of dictionaries is important since it decides which dictionary should be updated.

Since the two dictionaries do not have any common items, the merged dictionary contains the same key-value pairs. But if there are duplicate keys, then the keys of first dictionary are overwritten by those of the second dictionary.

for i in d3.keys():
d1[i]=d3[i]
print(d1) # output is {'a': 1, 'b': 5, 'e': 6}

for i in d1.keys():
d3[i]=d1[i]
print(d3) # output is {'b': 2, 'e': 6, 'a': 1}

Although this method is longer compared to others, it gives you more control to selectively merge items, which is not available with any of the other methods.

5. Using |= operator

The |= operator also allows you to merge two dictionaries in Python quickly. It is also known as update operator and works like update() function seen above. It is slightly different from ‘|’ operator seen earlier, which returns a new dictionary. The |= updates one of the two dictionaries instead of creating a new one altogether. Here is an example to merge dictionaries d1 and d2.

d1 = {'a':1, 'b' : 2}
d2 = {'c':3, 'd' : 4}
d3 = {'b':5, 'e' : 6}

d1 |= d2
print(d1) # output is {'a': 1, 'b': 2, 'c': 3, 'd': 4}

On the other hand, if we switch d1 and d2 in above expression, it will update d2 instead of d1.

d2 |= d1
print(d2) # output is {'c': 3, 'd': 4, 'a': 1, 'b': 2}

If there are duplicate keys in the 2 dictionaries, then the keys of first dictionary are updated by those of the second dictionary. Here also order of dictionaries is important.

d3 |= d1
print(d3) # output is {'b': 2, 'e': 6, 'a': 1}

d1 |= d3
print(d1) # output is {'a': 1, 'b': 5, 'e': 6}

Conclusion

In this article, we have learnt how to merge two dictionaries in Python. It is important to consider the order of specifying dictionaries, if the solution does not create a new dictionary but overwrites one of the two dictionaries. It is also important, in case the two dictionaries have duplicate keys. If the two dictionaries do not have any duplicate keys and your method gives a new dictionary then the order of dictionaries does not matter. Keeping these factors in mind, go through the above solutions one by one and pick the method that fits your requirement.

Also read:

How to Split List Into Even Chunks in Python
How to Backup MySQL Database in Python
What Does Name-Main Idiom Do in Python
What Are Metaclasses in Python

Leave a Reply

Your email address will not be published. Required fields are marked *