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.
**kwargs
keywordLet’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.
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)
In line 1, we create a function.
In lines 3 and 4, we create a loop which prints both the key
and value
of 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.