single
Arbitrary Keyword Arguments in Python
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.
123456def 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')
In this example, **kwargs receives named arguments and prints their keys and values.
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).
Swipe to start coding
Implement a function that filters products based on a given budget. The function should return a list of affordable products or indicate if no products are available within the budget.
- The function
filter_products_by_budgettakes abudgetand any number of named product–price pairs using**kwargs. - Inside the loop, use
kwargs.items()to get eachproductname and itsprice. - Compare the values and check if
budgetis greater than or equal toprice. - When the condition is true, store the product and its price in the
affordable_productsdictionary. - If the dictionary stays empty, return
"No products available within the budget.". - If at least one product is added, return
"Available products within budget: {affordable_products}".
Solution
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat