Learn
Learn Python: Function Arguments
Keyword Argument Unpacking

Python doesn’t stop at allowing us to accept unlimited positional parameters, it gives us the power to define functions with unlimited keyword parameters too. The syntax is very similar, but uses two asterisks (**) instead of one. Instead of args, we call this kwargs — as a shorthand for keyword arguments.

def arbitrary_keyword_args(**kwargs): print(type(kwargs)) print(kwargs) # See if there's an "anything_goes" keyword arg # and print it print(kwargs.get('anything_goes')) arbitrary_keyword_args(this_arg="wowzers", anything_goes=101) # Prints "<class 'dict'> # Prints "{'this_arg': 'wowzers', 'anything_goes': 101}" # Prints "101"

As you can see, **kwargs gives us a dictionary with all the keyword arguments that were passed to arbitrary_keyword_args. We can access these arguments using standard dictionary methods.

Since we’re not sure whether a keyword argument will exist, it’s probably best to use the dictionary’s .get() method to safely retrieve the keyword argument. Do you remember what .get() returns if the key is not in the dictionary? It’s None!

Instructions

1.

The string .format() method can utilize keyword argument syntax if you give placeholder names in curly braces in a string. For example:

"{place} is {adjective} this time of year.".format(place="New York", adjective="quite cold, actually")

Format the string in script.py within the print() statement. Give arguments for the placeholders given.

2.

create_products() takes a dictionary object and iterates over it, we can change it so that it uses keyword arguments instead. Update this function signature so products_dict contains all the keyword arguments passed to create_products().

3.

Update the call to create_products() to pass in each of those dictionary items as a keyword argument instead.

Folder Icon

Sign up to start coding

Already have an account?