🔹 1. Keyword Arguments (kwargs)
In Python, keyword arguments are passed to functions with a name=value pair, which improves readability and flexibility.
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet(name="Abhi", age=30)
Here, name
and age
are keyword arguments.
def register_customer(name, age, account_type="Savings", country="India"):
print(f"Customer: {name}")
print(f"Age: {age}")
print(f"Account Type: {account_type}")
print(f"Country: {country}")
# Calling with keyword arguments
register_customer(name="Abhi", age=35, country="USA")
You don’t have to follow the positional order.
Default values reduce the need for extra parameters every time.
**kwargs
for Dynamic Arguments:def print_details(**kwargs):
for key, value in kwargs.items():
print(f"{key} = {value}")
print_details(name="Abhi", age=35, city="Delhi", occupation="Data Scientist")
name = Abhi
age = 35
city = Delhi
occupation = Data Scientist
It allows us to construct dictionaries in a concise and readable way using comprehension syntax.
{key_expression: value_expression for item in iterable if condition}
squares = {x: x**2 for x in range(6)}
print(squares)
✅ Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
medicines = {
"Paracetamol": 50,
"Crocin": 0,
"Dolo": 20,
"Aspirin": 0,
"Cetrizine": 15
}
# Filter only available medicines using dictionary comprehension
available = {name: qty for name, qty in medicines.items() if qty > 0}
print(available)
✅ Output:
{'Paracetamol': 50, 'Dolo': 20, 'Cetrizine': 15}
employees = [("John", 30000), ("Abhi", 50000), ("Riya", 45000)]
salary_dict = {name: salary for name, salary in employees}
print(salary_dict)
✅ Output:
{'John': 30000, 'Abhi': 50000, 'Riya': 45000}
Feature | Keyword Arguments | Dict/List Comprehension |
---|---|---|
Syntax | func(name="Abhi", age=35) |
{k: v for k, v in iterable} |
Flexibility | High (order doesn’t matter) | High (inline dictionary creation) |
Use Case | Dynamic function input | Filtering or transforming dictionaries |
Real-world Example | Registering users, setting configs | Filtering available medicines, salary list |