Using the Python kwargs Variable in Function Definitions
00:00
Okay, now you’ve understood what *args
is for. What about **kwargs
? **kwargs
works just like *args
, but instead of accepting positional arguments, it accepts keyword, or named, arguments. For example, when you execute this script, the concatenate()
function will iterate through the Python kwargs
dictionary and concatenate all the values it finds. Like args
, kwargs
is just a name that can be changed to whatever you want. Again, what is important here is using the unpacking operator, which is the double asterisks (**
).
00:30
So, our example could be written like this. Note that in this example, the iterable object is a standard dictionary. If you iterate over the dictionary and want to return its values, then you must use the .values()
method. In fact, if you forget to use this method, you’ll find yourself iterating through the keys of your Python kwargs
dictionary instead, like in this example. Now, if you try to execute this code, you’ll notice the following output.
00:57
As you can see, if you don’t specify the .values()
method, your function will iterate over the keys of your Python kwargs
dictionary, returning the wrong result.
Mike K on June 7, 2020
@Zarata - Keyword arguments are dictionaries because you associate a name with a value. Here is the description of keyword arguments from the official documentation - keyword argument: an argument preceded by an identifier (e.g. name=) in a function call or passed as a value in a dictionary preceded by *.*
You will have to pass the whole dictionary to the function because keys and values alone are technically meaningless unless used together.
Become a Member to join the conversation.
Zarata on April 15, 2020
The examples show how one might access the keys OR the values of the dictionary, but that leaves the question of why one would pass a dictionary as a whole rather than just keys or values. Have you a good example of how having each map item as a whole is uniquely useful within a function?