Passing Dictionaries as Flexible Arguments
In addition to passing tuples as flexible arguments, you can also pass dictionaries as flexible arguments to Python functions. This is done using the **
prefix, which collects the keyword arguments into a dictionary.
Unpacking Dictionaries
Consider the following example:
def greet(name, greeting):
print(f"{greeting}, {name}!")
person = {"name": "Alice", "greeting": "Hello"}
greet(**person) ## Output: Hello, Alice!
In this case, the person
dictionary is "unpacked" into the name
and greeting
parameters of the greet()
function.
Passing Dictionaries of Varying Keys
You can also use the **kwargs
syntax to accept a variable number of keyword arguments, which can be useful when working with dictionaries of varying keys.
def print_person_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_person_info(name="Alice", age=30, city="New York")
## Output:
## name: Alice
## age: 30
## city: New York
In this example, the print_person_info()
function can accept any number of keyword arguments, and they are all collected into the kwargs
dictionary.
Combining Positional, Keyword, and Variable Arguments
You can also combine positional arguments, keyword arguments, and variable arguments in a single function. The variable arguments must be defined last in the function's parameter list.
def greet(greeting, *names, **info):
for name in names:
print(f"{greeting}, {name}!")
for key, value in info.items():
print(f"{key}: {value}")
greet("Hello", "Alice", "Bob", name="Charlie", age=30)
## Output:
## Hello, Alice!
## Hello, Bob!
## name: Charlie
## age: 30
In this case, the greeting
parameter is a positional argument, the *names
parameter collects all the remaining positional arguments into a tuple, and the **info
parameter collects all the keyword arguments into a dictionary.
By understanding how to pass dictionaries as flexible arguments, you can write more powerful and adaptable Python functions.