How do I merge two dictionaries in a single expression in Python?

Better Stack Team
Updated on January 24, 2023

To merge two dictionaries in a single expression you can use the dictionary unpacking operator **. This creates a new dictionary and unpacks all key-value pairs into the new dictionary. Let’s look at the example below.

x = {'firstname': 'John'}
y = {'lastname': 'Doe'}

z = {**x,**y}
Copied!

This will create a new dictionary z with the value of {'firstname': 'John', 'lastname': 'Doe'}.

Using OR operator

If you are using python 3.9.0 or greater, you can also use the bitwise OR operator also known as a pipe operator.

z = x | y
Copied!

The result will be the same.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack