Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Arbitrary Keyword Arguments | Arbitrary Arguments
Python Functions Tutorial
Section 3. Chapter 2
single

single

bookArbitrary Keyword Arguments

Swipe to show menu

In programming, there is a special syntax for passing any number of named parameters to a function, known as **kwargs.

**kwargs allows a function to accept any number of named arguments and treat them as a dictionary.

123456
def example_function(**kwargs): for key, value in kwargs.items(): print(f'{key}: {value}') # Example function call example_function(name='John', age=25, city='New York')
copy

In this example, **kwargs receives named arguments and prints their keys and values.

Note
Note

The .items() method is used to obtain a list of key-value pairs from a dictionary in Python. Each element in this list is represented as a tuple (key, value).

You can also use **kwargs to filter data based on a condition. For example, keeping only the entries whose value meets a certain threshold:

12345678
def filter_by_value(threshold, **kwargs): result = {} for key, value in kwargs.items(): if value >= threshold: result[key] = value return result print(filter_by_value(50, apple=30, banana=60, cherry=80))
copy

Here, result is built by checking each key-value pair and adding only those that meet the condition.

Task

Swipe to start coding

Implement a filter_products_by_budget function that filters products based on a given budget.

  • The function takes budget as a required argument and **kwargs, where each key is a product name and each value is its price.
  • Return a dictionary of products whose price does not exceed the budget.
  • If no products are within the budget, return "No products available within the budget.".
  • If at least one product is found, return "Available products within budget: {affordable_products}".

Solution

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 2
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt