Merge Two Python Dictionaries in a Single Expression

Merge Two Python Dictionaries in a Single Expression

In Python, you can merge two dictionaries in many different ways - but thanks to the introduction of Python 3.5, there are a couple of interesting ways you can merge two dictionaries in a single expression.

Note: Just to clarify, merging two dictionaries implies creating a new dictionary that contains merged values from the original dictionaries. If those two dictionaries have some of the same keys, values from the second dictionary will overwrite corresponding values from the first dictionary.

Assume you have two Python dictionaries - a and b:

a = {
    'name': "John",
    'surname': "Doe",
    'age': 32

b = {
    'name': "Robert",
    'profession': "Software Developer",
    'experience': 5

Now let's take a look at two different ways you can merge those two dictionaries.

Python 3.5 Solution - Dict Unpacking

Python 3.5 introduced the concept of dict unpacking which we can use to merge two dictionaries into one:

c = {**a, **b}

Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

This will give us the exact result we were expecting:

{'name': 'Robert', 'surname': 'Doe', 'age': 32, 'profession': 'Software Developer', 'experience': 5}

Notice that most of the object properties were merged as expected, although since both objects contained the name key, the second object (i.e. b) had its name in the resulting object.

Python 3.9 Solution - Dict Merge Operator

As you've probably noticed, the dict unpacking syntax is a bit off - it can be a bit hard to read and understand what's going on. That's why Python 3.9 introduced a new, but a similar concept - dict merge operator, also known as the dict union operator (|).

This operator can also be used to merge our two dictionaries together, which will give us the same result as the dict unpacking:

c = a | b
# Output:
# {'name': 'Robert', 'surname': 'Doe', 'age': 32, 'profession': 'Software Developer', 'experience': 5}

This gives us the same exact result as before, down to how it handles objects with the same key, such as name here.

Advice: If you want to learn more about Python dictionaries, you should consider reading our "Guide to Dictionaries in Python".

Last Updated: August 16th, 2022
Was this helpful?

Building Your First Convolutional Neural Network With Keras

# python# artificial intelligence# machine learning# tensorflow

Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...

David Landup
David Landup

Data Visualization in Python with Matplotlib and Pandas

# python# pandas# matplotlib

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

David Landup
David Landup

Ā© 2013-2022 Stack Abuse. All rights reserved.