What is the **kwargs keyword in Python?
In this shot, we will discuss the **kwargs keyword in Python. Python functions are built to lessen the redundancy of the same program and make the code reusable. Usually a function is written with a specific value called an argument. However, that sometimes creates problems if the number of arguments is not known.
The **kwargs keyword
Let’s say we want to create a function which gives us the name and age of a person. In this case, we might not know how many variables we want to add. We use **kwargs to address this problem.
**kwargs allows us to pass a variable number of keyword arguments to the function by using double asterisk ** before the parameter name. The arguments are passed as a dictionary. **kwargs is a special keyword that makes the function flexible.
Code
Let’s look at the code snippet to understand this better.
def intro(**data):for key, value in data.items():print(f"{key} is {value}")intro(Name="Tom", Age=25)intro(Name="Jerry", Age=26)
Explanation
-
In line 1, we create a function.
-
In lines 3 and 4, we create a loop which prints both the
keyandvalueof the input dictionary. -
In lines 6 and 7, we run the function using sample inputs.
In this way, we can use the **kwargs keyword in Python.