How to merge two dictionary in Python

In this article, we will learn to Merge Dictionaries in Python. Dictionary is a powerful data structure in Python which provides a .update() method. This method updates the current dictionary.Arguments include a dictionary which is to be merged with the current dictionary. So let’s start learning how to merge two dictionary in Python.

You can learn: Defaultdict, OrderedDict from Collections module of Python

Let’s get into code now.

Merge two dictionary in Python using update() method

Let us assume two dictionaries dict_1 and dict_2 which store their Keys and values as

dict_1 = {'a': 1,'b':2}
dict_2 = {'c': 3,'d':3}

Now we use the .update() method as to update dict_2 with dict_1 as in below code.

dict_2.update(dict_1)
print(dict_2)

In the above code dict_2 updates itself with the values of dict_1. However, we could also update dict_1 with the values of dict_2 which we can do using .update() method.

Now let’s look into the other method

Merging dictionary using Kwargs

The assumptions are the same about the dictionaries which are dict_1 and dict_2. Let us define a new dictionary as dict_3 which will have the updated values as:

dict_3 = {**dict_1,**dict_2}
print(dict_3)

Here we show up with Kwargs which is detailed under the argument section of the below link Kwargs in Python3. As here we sequentially pass the dictionaries to the third dictionary which
can be understood as dict_2 is the last one to pass So, dict_1 is updated with the values of dict_2 and then get stored into dict_3.
Definition:
**kwargs allows for any number of parameters which will be in a dictionary.

Leave a Reply

Your email address will not be published. Required fields are marked *