two green and yellow pear fruits
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.