Some text some message..
Back 9.1 Keyword Arguments (kwargs) & List Comprehension in Dictionary 26 Jun, 2025

🔹 1. Keyword Arguments (kwargs)

✅ What are Keyword Arguments?

In Python, keyword arguments are passed to functions with a name=value pair, which improves readability and flexibility.

✅ Syntax:

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.


✅ Practical Use Case:

🏦 Banking System – Customer Registration

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")

💡 Benefit:

  • You don’t have to follow the positional order.

  • Default values reduce the need for extra parameters every time.


✅ Using **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")

✅ Output:

name = Abhi
age = 35
city = Delhi
occupation = Data Scientist

🔹 2. List Comprehension in Dictionary

✅ What is Dictionary Comprehension?

It allows us to construct dictionaries in a concise and readable way using comprehension syntax.

✅ Syntax:

{key_expression: value_expression for item in iterable if condition}

✅ Practical Use Case:

📚 Example: Creating a Dictionary of Squares

squares = {x: x**2 for x in range(6)}
print(squares)

✅ Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}


✅ Real-World Use Case:

🏥 Pharmacy Inventory Filter

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}

🛠️ Use Case: Convert List of Tuples into Dictionary

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}

🧠 Summary Table:

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