Practical Applications of Lambda for Dictionaries
Filtering Dictionaries
You can use lambda functions with the filter()
function to filter dictionaries based on certain conditions. For example, let's say you have a dictionary of product prices and you want to filter out the products with a price greater than 50:
products = {'apple': 30, 'banana': 40, 'cherry': 60, 'durian': 70}
expensive_products = dict(filter(lambda item: item[1] > 50, products.items()))
print(expensive_products)
## Output: {'cherry': 60, 'durian': 70}
In this example, the lambda function lambda item: item[1] > 50
checks if the value (item[1]) is greater than 50, and the filter()
function returns a filter object containing the key-value pairs that match the condition. We then use the dict()
function to convert the filter object back into a dictionary.
Sorting Dictionaries
You can also use lambda functions with the sorted()
function to sort dictionaries based on their keys or values. For example, let's sort the products
dictionary by value in descending order:
sorted_products = dict(sorted(products.items(), key=lambda item: item[1], reverse=True))
print(sorted_products)
## Output: {'durian': 70, 'cherry': 60, 'banana': 40, 'apple': 30}
In this example, the lambda function lambda item: item[1]
extracts the value (item[1]) from each key-value pair, and the sorted()
function uses this to sort the dictionary. The reverse=True
argument sorts the dictionary in descending order.
Lambda functions can be used to transform the values in a dictionary. For example, let's say you have a dictionary of temperatures in Celsius and you want to convert them to Fahrenheit:
temperatures = {'New York': 20, 'London': 15, 'Tokyo': 25}
fahrenheit_temps = dict(map(lambda item: (item[0], (item[1] * 9/5) + 32), temperatures.items()))
print(fahrenheit_temps)
## Output: {'New York': 68.0, 'London': 59.0, 'Tokyo': 77.0}
In this example, the lambda function lambda item: (item[0], (item[1] * 9/5) + 32)
takes a key-value pair, converts the Celsius temperature to Fahrenheit, and returns a new key-value pair. The map()
function applies this lambda function to each item in the dictionary, and the dict()
function converts the resulting map object back into a dictionary.
These are just a few examples of how you can use lambda functions to work with dictionaries in Python. The flexibility and conciseness of lambda functions make them a powerful tool for manipulating and transforming data stored in dictionaries.