How to merge two dictionaries with Python

January 13, 2022

How to merge two dictionaries with Python

In this article, we’ll learn ways to merge two dictionaries with Python, so you have alternatives when performing this action.

merge two dictionaries with Python cover

Hey you programmers, okay? Let’s learn more about Python!

Let’s say we have two dictionaries:

x = {'a':1, 'b':2, 'c':3}
y = {'d':4, 'e':5, 'f': 6}

The first form we’re going to use was added to Python in its 3.5 version

And it’s very simple to be performed, check it out:

newDict = {**x, **y}

print(newDict) # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}

Remembering that this operator will only work in Python 3.5+ versions

But it’s a very simple way, we just use these special notations in each of the dictionaries

And Python will merge it, as shown in the print

And we don’t need to just do it with variables, see another example:

anotherDict = { **newDict, 'test': 'testing', 'x': 100}

print(anotherDict) # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'test': 'testing', 'x': 100}

Cool, isn’t  it??


In Python 3.9 a new way to do this action is being studied, this version of Python should be out around October 2020

The syntax will be:

dic3 = dic1 | dic2

It is left to be seen if it will actually be implemented, but until then use the version mentioned in the article


In this article we learn how to join two dictionaries with Python

We use a special syntax for this, which consists of adding the two dictionaries to a variable with two * in front, between braces

See the syntax summary:

x = { **y, **z }

Furthermore, we learned  that it is not necessary to use variables, we can create the new dictionary with its literal notation

Want to learn more about Python? Click here!

Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x