Merge two dictionaries in Python using update and double star

In this tutorial, we will learnĀ how to merge two dictionaries in Python using update and double star method.

There are a number of ways in Python, to merge two dictionaries created by the user. We will see the methods using simple examples.

Merging two dictionaries in Python

The first method by which we can merge dictionaries is by using the syntax update(). Let us first declare two dictionaries.

# Dictionary 1
dict1 = {'a':1, 'b':2, 'c':3}

# Dictionary 2
dict2 = {'c':4, 'e':5, 'f':6}

Here, we have declared the two dictionaries. Note that one key is common in both the dictionaries. Let us now merge the two dictionaries.

# Merging the two dictionaries
dict1.update(dict2)
print(dict1)

Output:

{'a': 1, 'b': 2, 'c': 4, 'e': 5, 'f': 6}

As a result, we can see that the two dictionaries have been merged. The value of the common key gets updated by the value in dict2, so the value in dict1 gets overwritten. Also, in this method we can see that there is no new dictionary created, the first dictionary itself gets updated with the values of the second dictionary.

If we want to create a new dictionary after merging two dictionaries, we can use the method of Kwargs/ double star **.

When we use the double stars method, it converts a dictionary into a collection of key value pairs. Then it merges these collections into a new dictionary.

# Merging contents of both dictionaries into dict3
dict3 = {**dict1, **dict2}
print('dict3:',dict3)

Output:

dict3: {'a': 1, 'b': 2, 'c': 4, 'e': 5, 'f': 6}

Hence, a new dictionary dict3 is created with all the contents of the two dictionaries to be merged.

Leave a Reply

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