**kwargs looks very similar to its
*args counterpart. Since
** generates a standard dictionary, we can use iteration just like we did earlier by taking advantage of the
.values() method. Here is an example:
def print_data(**data): for arg in data.values(): print(arg) print_data(a='arg1', b=True, c=100)
arg1 True 100
We can also combine our use of
** with regular positional arguments. However, Python requires that all positional arguments come first in our function definition. Let’s examine how this works:
def print_data(positional_arg, **data): print(positional_arg) for arg in data.values(): print(arg) print_data('position 1', a='arg1', b=True, c=100)
position 1 arg1 True 100
If we were to switch the position of
positional_arg to come after
**data, we would be met with a
Let’s expand our restaurant application from the previous exercises to apply the flexibility of using
**kwargs in our functions.
In the last exercise, we saw how using
** allowed us to capture different food items that a table will order. In the next few checkpoints, we will finish implementing the functionality of our
Take some time to get reacquainted with the program. Note the changes in the
Run the code to move on!
Unfortunately, when we originally implemented
assign_food_items we did not assign the values we capture into our
Adjust the function definition of
- Add a positional parameter called
table_numberfollowed by the
**order_itemsparameter we already defined.
- Uncomment the 2 lines inside the function.
Adding the parameter and uncommenting the lines will now allow us to assign the food to a specific table.
Great! Now that we have the base functionality set up, let’s give it a test run. Luckily a new customer named Douglas just came in and is ready to place an order.
print('\n --- tables after update --- \n'), call the
assign_food_items() function with the following arguments:
- A positional argument
table_numberwith the value
- A keyword argument
foodwith the value
'Seabass, Gnocchi, Pizza'
- A keyword argument
drinkswith the value
tables to see the change!