/  Technology   /  How do I merge two dictionaries in a single expression?

How do I merge two dictionaries in a single expression?

Dictionary is an unordered collection of data in the form of key-value pairs separated by commas inside curly brackets. Dictionaries are indexed by keys. They are generally optimized to retrieve values when the key is known. Values (definitions) are mapped to a specific key (words) similar to that of a dictionary in the real world. 

Now coming back to the question, we can merge two dictionaries using two different ways based on the version of Python we are using.

For all the versions above Python 3.4, a new syntax has been updated to merge two dictionaries i.e.

 {**dictionary_name_1, **dictionary_name_2}

Let’s take an example of two dictionaries x and y with the following keys and values.

And now we take a new dictionary z in which we’ll store the two merged dictionaries. As we can see, when we print z, it is returning keys and values in both dictionaries x and y.

Now for all the versions below 3.5, the above syntax is not valid so we use two different functions namely copy() and update().

First, we create a shallow copy of x’s keys and values and store it in z.

Z = x.copy()

And after this, we update z using the keys and values of y.

z.update(y)

We can use these by putting them into a function, here merge_two_dicts() and take in our two dictionaries x and y as arguments.

Leave a comment