Merge Dictionaries in Python

While programming, there may be situations where we need to merge two or more dictionaries in python. In this article, we will study how we can merge two or more dictionaries in python using different ways.

Merge dictionaries using items() method.

We can merge two dictionaries using items() method by adding items of a dictionary to another dictionary one by one. The items() method when invoked on a dictionary, returns a list of tuples containing the key-value pair. If we have to merge two dictionaries, we will take items of a dictionary one by one and add it to another dictionary as follows.

dict1={1:1,2:4,3:9}
print("First dictionary is:")
print(dict1)
dict2={4:16,5:25,6:36}
print("Second dictionary is:")
print(dict2)
for key,value in dict2.items():
    dict1[key]=value
print("Merged dictionary is:")
print(dict1)

Output:

First dictionary is:
{1: 1, 2: 4, 3: 9}
Second dictionary is:
{4: 16, 5: 25, 6: 36}
Merged dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}

While using the above method, we have to consider the point that if there are common keys between the two dictionaries, the final dictionary will have common keys with values from the second dictionary from which we have extracted the items. Also only the first dictionary, to which the items are being added gets modified and nothing happens to the second dictionary.

Merge dictionaries using popitem() method.

The popitem() method is used to delete an item from a python dictionary. When invoked on a dictionary the popitem() method deletes the most recently added item in the dictionary and returns the item in the form of a tuple as key value pair.

To merge the dictionaries, we will pop the items from a dictionary using the popitem() method and will keep adding it to another dictionary.

dict1={1:1,2:4,3:9}
print("First dictionary is:")
print(dict1)
dict2={4:16,5:25,6:36}
print("Second dictionary is:")
print(dict2)
while dict2:
    key,value=dict2.popitem()
    dict1[key]=value
print("Merged dictionary is:")
print(dict1)

Output:

First dictionary is:
{1: 1, 2: 4, 3: 9}
Second dictionary is:
{4: 16, 5: 25, 6: 36}
Merged dictionary is:
{1: 1, 2: 4, 3: 9, 6: 36, 5: 25, 4: 16}

While using the above method, we have to keep in mind that both the dictionaries which are to be merged get modified. The second dictionary from which the items are being pooped out becomes empty while the first dictionary to which items are being added also gets modified. Again, we will have to consider the point that if there are common keys between the dictionaries which are being merged, the merged dictionary will contain values from the second dictionary from which the items were popped out for the common keys.

Using keys() method.

We can also use keys() method to merge two dictionaries in python. The keys() method when invoked on a dictionary, returns the list of keys in the dictionary. We will use the keys() method to take all the keys from a dictionary and after that we can access the associated values of the keys. After that we can add the key value pair into another dictionary as follows.

dict1={1:1,2:4,3:9}
print("First dictionary is:")
print(dict1)
dict2={4:16,5:25,6:36}
print("Second dictionary is:")
print(dict2)
keylist=dict2.keys()
for key in keylist:
    dict1[key]=dict2[key]
print("Merged dictionary is:")
print(dict1)

Output:

First dictionary is:
{1: 1, 2: 4, 3: 9}
Second dictionary is:
{4: 16, 5: 25, 6: 36}
Merged dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}

When we merge two dictionaries using above method in python , we have to keep in mind that second dictionary from which we are getting the keys doesn’t get modified. Only the dictionary to which keys and values are getting added gets modified. Also, if the two dictionaries being merged have keys in common then the merged dictionary will have the values for the common keys from the dictionary from which the keys were obtained.

Merge dictionaries using update() method

We can directly merge a dictionary to another dictionary using update() method. The update() method is invoked on a dictionary and it takes another dictionary as input argument. We can merge the dictionaries using the update() method as follows.

dict1={1:1,2:4,3:9}
print("First dictionary is:")
print(dict1)
dict2={4:16,5:25,6:36}
print("Second dictionary is:")
print(dict2)
dict1.update(dict2)
print("Merged dictionary is:")
print(dict1)

Output:

First dictionary is:
{1: 1, 2: 4, 3: 9}
Second dictionary is:
{4: 16, 5: 25, 6: 36}
Merged dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}

In this case, when we merge two dictionaries using update() method in python, the common keys are assigned the values which are present in the dictionary which is passed as argument. Also the second dictionary which is passed as argument doesn’t get modified while the first dictionary on which the update() method is invoked gets modified and is turned into final dictionary.

Merge dictionaries using ** operator

Double asterisk (**) operator is used to pass variable length keyword parameters to a function. We can also use ** operator to merge two dictionaries. When we apply ** operator to a dictionary, it deserializes the dictionary and converts it to a collection of key value pairs and then a new dictionary is formed using the key value pairs.

dict1={1:1,2:4,3:9}
print("First dictionary is:")
print(dict1)
dict2={4:16,5:25,6:36}
print("Second dictionary is:")
print(dict2)
mergedDict={**dict1,**dict2}
print("Merged dictionary is:")
print(mergedDict)

Output:

First dictionary is:
{1: 1, 2: 4, 3: 9}
Second dictionary is:
{4: 16, 5: 25, 6: 36}
Merged dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}

We can merge any number of dictionaries at once using ** operator. Also, none of the original dictionaries which have to be merged are modified. They remain as it is. In this method too, when the dictionaries to be merged have common keys, the values for the respective keys will be taken from the dictionaries which come last in the sequence while merging.

Conclusion

In this article, we have seen how to merge dictionaries in python using different methods. We can also write the programs used in this article with exception handling using python try except to make the programs more robust and handle errors in a systematic way. Stay tuned for more informative articles.

Leave a Reply

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