Skip to content

Merge Python Dictionaries – 4 Different Ways

Merge Python Dictionaries Cover Image

In this post, you’ll learn how to merge Python dictionaries. You’ll learn different ways, allowing you to merge dictionaries all the way back to Python 3.4, including some new, more efficient ways of accomplishing this in Python 3.9.

Loading our Dictionaries

For this tutorial, we’ll use two dictionaries, dict_a and dict_b. Let’s start things off by creating them here:

dict_a = {
    'age': 31,
    'name': 'Nik'
}

dict_b = {
    'career': 'Python-enthusiast',
    'gender': 'Male'
}

dict_c = {
    'age': 32,
    'location': 'Toronto'
}

Now we can access dictionary items by either using square-bracket notation or, as a much safer alternative, using the .get() method:

>>> print(dict_a['age'])
>>> print(dict_b['gender'])

31
Male

The reason that the .get() method is considered safer is that it will return None if a key doesn’t exist. Using the square-bracket notation, on the other hand, will return an error, thereby causing your code to fail unless you build in an exception.

Check out some other Python tutorials on datagy, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas!

Merge Dictionaries in Python 3.9+ Using the Union Operator

Python 3.9 introduced a very handy (and syntactically beautiful) operator to merge two dictionaries. To learn more about this change, check out the Pep-584 documentation on the official Python website.

In order to use this change, make sure you’re running Python 3.9 or higher. Now let’s get to merging some dictionaries:

>>> merged_dict = dict_a | dict_b
>>> print(merged_dict)

{'age': 31, 'name': 'Nik', 'career': 'Python-enthusiast', 'gender': 'Male'}

Similarly, you can use the inplace operator to simplify your code even further. Say you wanted to updated dict_a by merging in the values of dict_b. Instead of writing dict_a = dict_a | dict_b, you could simply write:

>>> dict_a |= dict_b
>>> print(dict_b)

{'age': 31, 'name': 'Nik', 'career': 'Python-enthusiast', 'gender': 'Male'}

Now, you may be wondering what happens when your dictionaries share keys. The simple answer is that the values in the left-sided dictionary are replaced by those on the right side. This occurs since keys in dictionaries need to be unique.

In our sample dictionaries we have overlaps in keys in dict_a and dict_c. Let’s try merging them and see what happens:

>>> merged_dict = dict_a | dict_c
>>> print(merged_dict)

{'age': 32, 'name': 'Nik', 'location': 'Toronto'}

Merge Dictionaries in Python 3.5+ Using Unpacking

Python 3.5 introduced the ability to unpack variables using the unpacking operator **. The way this method works is to create a dictionary using the unpacked values of two or more dictionaries.

Similar to the method above, this will overwite any duplicate keys with the dictionary on the right.

Let’s give this a shot:

>>> merged_dict = {**dict_a, **dict_c}
>>> print(merged_dict)

{'age': 32, 'name': 'Nik', 'location': 'Toronto'}

Merge Dictionaries in Python 2 and 3 Using .update()

Finally, if you need to use an older version of Python, say Python 3.4 or earlier, you can use the .update() method.

What we’ll do, is first copy the dictionary into a new dictionary using the .copy() method. Then, we’ll use the .update() method inplace to merge the dictionaries:

>>> merged_dict = dict_a.copy()
>>> merged_dict.update(dict_c)
>>> print(merged_dict)

{'age': 32, 'name': 'Nik', 'location': 'Toronto'}

This can be a bit cumbersome to run. It may be prudent to write a function to accomplish this. We can do this by writing:

def merge_dicts(dict_1, dict_2):
    merged_dict = dict_1.copy()
    merged_dict.update(dict_2)

    return merged_dict

merged_dict = merge_dicts(dict_a, dict_b)

print(merged_dict)

This returns the following:

{'age': 31, 'name': 'Nik', 'career': 'Python-enthusiast', 'gender': 'Male'}

Conclusion

In this post, you learned how to merge Python dictionaries using multiple methods, depending on the version of Python you’re using. You learned how to use the union operator, the unpacking operator, and the .update() method.

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials.View Author posts

Tags:

Leave a Reply

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