0
0
Pythonprogramming~5 mins

Variable-length keyword arguments (**kwargs) in Python

Choose your learning style9 modes available
Introduction

Sometimes you want a function to accept any number of named inputs without knowing them all in advance. **kwargs lets you do that easily.

When writing a function that can take extra named options you don't know beforehand.
When you want to pass settings or parameters flexibly to another function.
When creating wrapper functions that forward named arguments to other functions.
When you want to collect all extra named inputs into one place for processing.
Syntax
Python
def function_name(**kwargs):
    # kwargs is a dictionary of named arguments
    for key, value in kwargs.items():
        print(f"{key} = {value}")

**kwargs collects extra named arguments into a dictionary inside the function.

You can use any name instead of kwargs, but kwargs is the common convention.

Examples
This function prints each name and greeting passed as named arguments.
Python
def greet(**kwargs):
    for name, greeting in kwargs.items():
        print(f"{name}: {greeting}")

greet(John='Hello', Mary='Hi')
Here, info is a dictionary with keys 'age' and 'city'.
Python
def show_info(**info):
    print(info)

show_info(age=30, city='Paris')
You can mix normal parameters with **kwargs. Extra named arguments go into kwargs.
Python
def example(a, b, **kwargs):
    print(a, b)
    print(kwargs)

example(1, 2, x=10, y=20)
Sample Program

This program defines a function that prints any pet details given as named arguments.

Python
def describe_pet(**kwargs):
    print("Pet details:")
    for key, value in kwargs.items():
        print(f"{key}: {value}")

describe_pet(name='Buddy', species='Dog', age=5)
OutputSuccess
Important Notes

You can combine *args and **kwargs in the same function to accept any number of positional and named arguments.

Inside the function, kwargs behaves like a normal dictionary.

Summary

**kwargs lets functions accept any number of named arguments as a dictionary.

Use it when you want flexible, optional named inputs.

Inside the function, access the arguments by their names as dictionary keys.