Argument Dictionary Packing and Unpacking
00:00 Just as you can use argument tuple packing and unpacking for dealing with positional parameters to a function, Python allows you to use something called argument dictionary packing and unpacking to do the same thing with keyword arguments.
The double asterisk (
**) is used to specify when dictionary packing or unpacking is going to occur. If you use the double asterisks in front of a parameter name in the definition of a function, you are indicating that you want dictionary packing to take any number of keyword arguments provided at the function call and pack them into a dictionary where the key-value pairs of the dictionary come from the keywords for the keys and the argument values for the values when the dictionary is created.
We typically use
kwargs, keyword args, for the parameter which will hold the dictionary when packed. Here is a simple function, where all we’re going to do is look at the dictionary created when this function is called using an arbitrary number of keyword arguments.
If you want to see this,
from argument_dictionary_packing we will import our function. Here, when we call our function, it’s expecting to perform dictionary packing on an unknown number of keyword arguments.
So we can say… We’ll create a keyword
foo, so the first parameter we’ll call
foo. We’ll set it equal to
1. Call the second parameter
bar, give it a value of
2. Call the third parameter
baz and give it a value of
02:12 And so we can see that each of those keyword arguments were packed into a dictionary, which we see here, and then we saw that we have a dictionary object and we could run through it seeing the key-value pairs coming from the keyword and argument value.
That would be a typical use for this particular function. So, we can define this dictionary. And again, we probably had a dictionary already created and have been doing other work with, and now we need to use this function
f() that is expecting just three parameters. But our dictionary has the key
'x', which maps to
'foo'. It has the key
'y', which maps to
And now we want to unpack that to use in
f() as three separate arguments, so I would unpack it using the two asterisk syntax, and we can see that
z were given those appropriate values.
Become a Member to join the conversation.