How To Use * * Kwargs In Python

In Python programming, we use two asterisks to collect keyword-value pair parameters. You can collect the keyword-value pair parameters into a dictionary.

The name of the parameter is the “key” of the dictionary, and the corresponding parameter value is the “value” of the dictionary. Let’s look at the following example, as the example shows, inside the function, the kwargs argument is a python dictionary object.

# Define a python function with keyword arguments( kwargs ).
>>> def print_kwargs(**kwargs):
       # Print out the kwargs argument value.
...    print(kwargs)

...
# Invoke the above python function and pass some key-value pair arguments.
>>> print_kwargs(name = 'hello',passwd = '12345678',email = 'hello@hello.com')
# The output is a python dictionary object's key and value.
{'name': 'hello', 'passwd': '12345678', 'email': 'hello@hello.com'}

When a python function is invoked with a lot of arguments, how can we know how parameters will be transferred? In fact, it’s easy to do. Just combine the * args and the * * kwargs as the python function last two arguments, then you can pass any number of arguments to the python function.

# Define the python function with 4 arguments, when you call this function, you can pass any number of arguments to the function.
>>> def print_all(x,y,*args,**kwargs):
       # Print out the 4 arguments value.
...    print(x)
...    print(y)
...    print(args)
...    print(kwargs)

...

# Pass only the first 2 arguments to the python function.
>>> print_all('hello',88888)
# This is argument x value.
hello
# This is argument y value.
88888
# The third and fourth arguments are empty.
()

{}

# Pass 3 arguments value.
>>> print_all('hello',1,2,3,4,5,6)
# The first argument value.
hello
# The second argument value.
1
# The third argument is a tuple.
(2, 3, 4, 5, 6)
# The fourth argument is empty.
{}

# Pass 4 arguments value.
>>> print_all('hello',1,2,3,4,5,6, like = 'python')
# The first argument value.
hello
# The second argument value.
1
# The third argument is a tuple.
(2, 3, 4, 5, 6)
# The fourth argument is a dictionary object.
{'like': 'python'}

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.