9. Double-star kwargs
**kwargs lets a function accept any number of keyword arguments. The ** before the parameter name collects them into a dictionary:
Inside the function, data is a dictionary: show(name="Ada", age=36) makes it {"name": "Ada", "age": 36}.
** does two jobs depending on where it appears:
- In the definition
def show(**data), it packs all keyword arguments into the dictionarydata. - In a call,
show(**{"name": "Ada", "age": 36})unpacks that dictionary into keyword arguments. It is exactly the same asshow(name="Ada", age=36).
You cannot call show({"name": "Ada", "age": 36}): that passes one positional argument, and def show(**data) only accepts keyword arguments.
*args from the previous lesson is the positional counterpart: def f(*numbers) packs positional arguments into a tuple, and f(*[1, 2, 3]) unpacks a list into positional arguments.
- Only keyword arguments are collected; positional arguments are not.
- The name
kwargsis a convention; the**is what matters. - Regular parameters,
*argsand**kwargscan be combined in that order.
Coming from JavaScript? **kwargs collects extra named options into a dict, not an object. At the call site, f(**data) spreads that dict into named arguments, similar to spreading an object into props.
Collect keyword arguments
Define show(**data) that loops over data.items() and prints each pair as key: value using an f-string. Call show(name="Ada", age=36).
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Count the keyword arguments
Define count_kwargs(**info). The ** collects the keyword arguments into the dictionary info, so len(info) returns how many keyword arguments were passed. The function should return that number.
Then print count_kwargs(a=1, b=2, c=3).
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Read one keyword argument
Define welcome(**info) that prints Welcome to <city> using info["city"]. Call welcome(city="Paris").
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Add the keyword values
Define total_points(**scores) that adds every value in scores with a for loop and returns the total. Print total_points(math=90, art=80).
Print exactly:
Create a free account to save your progress and unlock chapter 2.