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?

Real-Time Road Sign Detection with YOLOv5

# python# machine learning# computer vision# pytorch

If you drive - there's a chance you enjoy cruising down the road. A responsible driver pays attention to the road signs, and adjusts their...

David Landup
David Landup

Data Visualization in Python: The Collatz Conjecture

# python# matplotlib# data visualization

The Collatz Conjecture is a notorious conjecture in mathematics. A conjecture is a conclusion based on existing evidence - however, a conjecture cannot be proven....

David Landup
Jovana Ninkovic

© 2013-2022 Stack Abuse. All rights reserved.