Merge two dictionaries in a single expression in Python

In this post, we will learn how to merge two dictionaries in a single expression in Python. Merging is the process of combining two or more things into a single unit.

A dictionary is a collection of unordered keys and values. The values in a dictionary are changeable and can be accessed by an index number and key name.

Also, read: Convert a Python Dictionary into a List

In Python, there are many methods of merging two dictionaries. But here in this post, we will learn about one method that will merge given two dictionaries into a single expression.

Merge two dictionaries in a single expression

In Python for merging two dictionaries into a single expression, we use **(kwargs) with the dictionary name. We will store the resultant dictionary after merging it into a new dictionary. So to understand the process better, let’s see the example given below:

#Function to Merge two dictionary

def merge(dict1,dict2):
    merged={**dict1,**dict2}
    print(merged)

# Dictionary 1
dict1= {'Fruit': 'Banana','Perfume': 'Wildstone', 'Watch':'Apple'}

#Dictionary 2
dict2={'TCS':1968,'Wipro':1945,'Infosys':1981}

#Calling Function
merge(dict1,dict2)

Below is the output of our program:

{'Fruit': 'Banana', 'Perfume': 'Wildstone', 'Watch': 'Apple', 'TCS': 1968, 'Wipro': 1945, 'Infosys': 1981}

Actually **kwarg is a method of passing keyworded variable-length argument.  It allows passing whole keys and values of the dictionary through keyword arguments.  So we can say that it actually write the keys and values of both dictionaries into third.

I hope you understood how to merge two dictionaries into a single expression in Python. If you have any doubts related to this post or you find anything wrong, please provide your suggestion in the comment section of this post.
For a tutorial on any other topics of Python comment below your topic name.

Also Read: Python isprintable() method

Thank You.

 

Leave a Reply

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