How to Merge Dictionaries in Python

opened book on brown table

The most common way to merge two dictionaries in Python is using the update() method:

dict1.update(dict2)

This code merges the dict1 to the end of dict2. It does not create a new dictionary.

This approach works with Python 2 and Python 3, so it’s the “safest bet” when merging two dictionaries.

But there are other modern approaches to merging dictionaries too. Please, read along to learn more.

Merge Dictionaries in Python Using the update() Method

Using update() method to merge dictionaries adds a dictionary to the end of another one.

To merge two dictionaries using the update() method, you need to have two dictionaries. Then call .update() on one of the dictionaries and pass the other into the call.

For example, let’s create two dictionaries dict1 and dict2 and merge the second one into the first one:

dict1 = {'a': 1, 'b': 2}
dict2 = {'d': 3, 'c': 4}

dict1.update(dict2)

print(dict1)

Output:

{'a': 1, 'b': 2, 'd': 3, 'c': 4}

But this way you modify one of the original dictionaries. To avoid this, you should create a function that takes two dictionaries, merges them, and returns a new one.

Consider implementing the following function into your codebase:

def merge_dicts(a, b):
    c = a.copy()
    c.update(b)
    return c

This function copies the contents of the dictionary a, and merges it with b and returns the result. This way the original dictionary stays the same.

Now you can use this approach to merge two dictionaries:

dict1 = {'a': 1, 'b': 2}
dict2 = {'d': 3, 'c': 4}

dict3 = merge_dicts(dict1, dict2)

print(dict3)

Output:

{'a': 1, 'b': 2, 'd': 3, 'c': 4}

Merge Dictionaries Using Double Star **

As of Python 3.5, it has been possible to use double star (**) to merge two dictionaries.

dict1 = {'a': 1, 'b': 2}
dict2 = {'d': 3, 'c': 4}

dict3 = {**dict1, **dict2}

print(dict3)

Output:

{'a': 1, 'b': 2, 'd': 3, 'c': 4}

This works because the ** operator unpacks the contents of the dictionaries. It creates a new dictionary based on the elements of the two unpacked dictionaries.

To better understand how it works, please refer to **kwargs in Python.

Merge Dictionaries in Python Using | Operator (Python 3.9+ Only)

This is a fairly new approach to merging dictionaries in Python introduced in Python version 3.9.

To merge two (or more) dictionaries, you can use the | operator between dictionaries to merge them. This operation creates a completely new dictionary that combines the old dictionaries.

For instance:

dict1 = {'a': 1, 'b': 2}
dict2 = {'d': 3, 'c': 4}

dict3 = dict1 | dict2

print(dict3)

Output:

{'a': 1, 'b': 2, 'd': 3, 'c': 4}

Conclusion

Thanks for reading. Happy coding!

Further Reading

50 Python Interview Questions

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

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