**kwargs in python

**kwargs is used when we want to pass variable length keyworded arguments to a function. A keyworded arguments will have a key value pair like name=”John” or {“name”:”John”}.

Let us look into **kwargs with two examples. In the first example we will pass keyworded arguments of variable length. In the next example we will pass a dictionary to the function. Just like *args , **kwargs is also a name we can give whatever name we want, like **details or **info , etc.

Example 1

**kwargs in python

The output of the above code is,

name John David
age 24
occupation Doctor

The items() functions unpacks the **kwargs values as ‘<class ‘dict_items’>. If we try to print the **kwargs.items() it will print a list of tuples like this.

dict_items([('name', 'John David'), ('age', 24), ('occupation', 'Doctor')])

We can iterate the list to get key, value from each tuple and print it.

Example 2

In this example we will pass a dictionary to the function instead of keyworded arguments. Let us look at the example.

**kwargs with dictionary

This example will print,

name John David
age 24
job Musician

which is same as the first example. The only difference is we are passing a dictionary to the function.

Conclusion

*args and **kwargs are used when we want to deal with variable keyword arguments. Use this to stop making changes often in function calling and function definition when there is a change in the number of keyword arguments.

In other words a *args is suitable for list and **kwargs is suitable for a dictionary data type. Make your code simple and elegant with this feature.

You can read more about *args in our previous article.