How to Quickly Merge 2 Dictionaries in Python

A guide on how to merge two dictionaries in Python.

Fatos Morina
Python in Plain English
1 min readJan 12, 2022

--

Photo by Teslariu Mihai on Unsplash

Dictionaries represent a commonly used data structure in many scenarios. You may also have cases when you need to merge 2 dictionaries, for example, given that we have 2 equal keys, we want to get the value of the second dictionary.

To illustrate that, let us assume that we have the following dictionaries:

Now we want to only keep values from the second dictionary. To do this merge, we can do it in multiple ways.

In Python 2, we can initially copy the first dictionary, and then update it with the second dictionary:

If you are using Python 3.5 or above, you can use the following:

If you are using Python 3.9 or above, then you can use a pretty neat trick and merge 2 dictionaries using a vertical pipe:

That’s pretty much it for this article. I found you find this useful.

More content at plainenglish.io. Sign up for our free weekly newsletter. Get exclusive access to writing opportunities and advice in our community Discord.

--

--