python kwargs
satya - 3/3/2024, 2:49:41 PM
Two purposes for kwargs in python
satya - 3/3/2024, 2:51:10 PM
Unpacking dictionaries
def greet(first_name, last_name):
print(f"Hello, {first_name} {last_name}!")
person = {"first_name": "John", "last_name": "Doe"}
# Unpacks the person dictionary
# into the first_name and last_name arguments
greet(**person)
satya - 3/3/2024, 2:53:41 PM
A function that takes an arbitrary number of key value arguments
#Definition
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
# Can accept any number of keyword arguments
print_info(name="John Doe", age=30, country="USA")
satya - 3/3/2024, 2:56:07 PM
You can call the function this way too
info = {"name": "John Doe", "age": 30, "country": "USA"}
# Pass the dictionary as individual key/value pairs using **
print_info(**info)
satya - 3/3/2024, 2:58:50 PM
In summary