Using the Python kwargs Variable in Function Definitions
Okay, now you’ve understood what
*args is for. What about
**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
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 (
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.
Become a Member to join the conversation.