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

How do I merge two dictionaries in a single expression in Python?

 

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.

 

Example:

x={'a':'one', 'b':'two', 'c':'three'}
y={'d':'four', 'e':'five', 'f':'six'}

 

Output:

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.

 

Example:

x={'a':'one', 'b':'two', 'c':'three'}
y={'d':'four', 'e':'five', 'f':'six'}

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

 

Output:

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)

 

Example:

x={'a':'one', 'b':'two', 'c':'three'}
y={'d':'four', 'e':'five', 'f':'six'}
z = x.copy()   # creates a shallow copy of x's keys and values
z.update(y)    # updates or adds z with y's keys and values & returns None
print(z)

 

Output:

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.

 

Example:

x={'a':'one', 'b':'two', 'c':'three'}
y={'d':'four', 'e':'five', 'f':'six'}
def merge_two_dicts(x, y):
   z = x.copy()
   z.update(y)
   print(z)

 

Output:

Leave a comment