You can merge two dictionaries into a new one using several methods depending on your Python version.

When a key exists in both dictionaries, the second dictionary’s value overwrites the first.

Python 3.9+ — Using the | Operator

Starting from Python 3.9, you can use the merge (|) and update (|=) operators:

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}

z = x | y
print(z)

Output:

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

| creates a new merged dictionary.
|= updates the existing one (similar to .update()).

Python 3.5+ — Using Dictionary Unpacking (**)

For Python 3.5 and later:

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}

z = {**x, **y}
print(z)

Output:

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

Here, unpacking (**) expands both dictionaries into a new one, and values from y overwrite duplicates from x.

Older Versions (Python 2.x or Early 3.x)

If you’re using an older version of Python:

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}

z = x.copy()
z.update(y)

print(z)

Output:

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

Notes

  • Use | or ** for new merged dictionaries.
  • Use .update() or |= for in-place updates.
  • When keys overlap, values from the right-hand dictionary take precedence.

Need Help With Python Development?

Work with our skilled Python developers to accelerate your project and boost its performance.

Hire Python Developers

Support On Demand!

Related Q&A