Let's explore some more advanced applications of lambda functions with dictionaries, focusing on sorting and transforming dictionary data.
Sorting Dictionaries with Lambda Functions
Dictionaries in Python are not ordered by default, but sometimes we need to process them in a specific order. Let's create a new file called advanced_dictionary_ops.py
in the /home/labex/project
directory and add the following code:
## Create a dictionary of student scores
student_scores = {
'Alice': 92,
'Bob': 85,
'Charlie': 78,
'David': 95,
'Eva': 88
}
print("Original student scores:", student_scores)
## Sort by student names (keys)
sorted_by_name = dict(sorted(student_scores.items()))
print("\nSorted by name:", sorted_by_name)
## Sort by scores (values) in ascending order
sorted_by_score_asc = dict(sorted(student_scores.items(), key=lambda item: item[1]))
print("\nSorted by score (ascending):", sorted_by_score_asc)
## Sort by scores (values) in descending order
sorted_by_score_desc = dict(sorted(student_scores.items(), key=lambda item: item[1], reverse=True))
print("\nSorted by score (descending):", sorted_by_score_desc)
## Get the top 3 students by score
top_3_students = dict(sorted(student_scores.items(), key=lambda item: item[1], reverse=True)[:3])
print("\nTop 3 students:", top_3_students)
Run the file:
python3 advanced_dictionary_ops.py
You should see output similar to:
Original student scores: {'Alice': 92, 'Bob': 85, 'Charlie': 78, 'David': 95, 'Eva': 88}
Sorted by name: {'Alice': 92, 'Bob': 85, 'Charlie': 78, 'David': 95, 'Eva': 88}
Sorted by score (ascending): {'Charlie': 78, 'Bob': 85, 'Eva': 88, 'Alice': 92, 'David': 95}
Sorted by score (descending): {'David': 95, 'Alice': 92, 'Eva': 88, 'Bob': 85, 'Charlie': 78}
Top 3 students: {'David': 95, 'Alice': 92, 'Eva': 88}
In this example, we used the sorted()
function with lambda functions to sort the dictionary in different ways:
- By key (student name)
- By value (score) in ascending order
- By value (score) in descending order
We also used slicing [:3]
to get only the top 3 students after sorting.
Now, let's look at how we can transform the values in a dictionary. Add the following code to your advanced_dictionary_ops.py
file:
print("\n--- Transforming Dictionary Values ---")
## Create a dictionary of temperatures in Celsius
celsius_temps = {
'New York': 21,
'London': 18,
'Tokyo': 26,
'Sydney': 22,
'Moscow': 14
}
print("Temperatures in Celsius:", celsius_temps)
## Convert Celsius to Fahrenheit: F = C * 9/5 + 32
fahrenheit_temps = {city: round(temp * 9/5 + 32, 1) for city, temp in celsius_temps.items()}
print("Temperatures in Fahrenheit:", fahrenheit_temps)
## Categorize temperatures as cool, moderate, or warm
def categorize_temp(temp):
if temp < 18:
return "Cool"
elif temp < 25:
return "Moderate"
else:
return "Warm"
categorized_temps = {city: categorize_temp(temp) for city, temp in celsius_temps.items()}
print("Categorized temperatures:", categorized_temps)
## Group cities by temperature category using a lambda and reduce
from collections import defaultdict
from functools import reduce
grouped_cities = reduce(
lambda result, item: result[categorize_temp(item[1])].append(item[0]) or result,
celsius_temps.items(),
defaultdict(list)
)
print("\nCities grouped by temperature category:")
for category, cities in grouped_cities.items():
print(f"{category}: {', '.join(cities)}")
Run the file again:
python3 advanced_dictionary_ops.py
You should now see additional output:
--- Transforming Dictionary Values ---
Temperatures in Celsius: {'New York': 21, 'London': 18, 'Tokyo': 26, 'Sydney': 22, 'Moscow': 14}
Temperatures in Fahrenheit: {'New York': 69.8, 'London': 64.4, 'Tokyo': 78.8, 'Sydney': 71.6, 'Moscow': 57.2}
Categorized temperatures: {'New York': 'Moderate', 'London': 'Moderate', 'Tokyo': 'Warm', 'Sydney': 'Moderate', 'Moscow': 'Cool'}
Cities grouped by temperature category:
Cool: Moscow
Moderate: New York, London, Sydney
Warm: Tokyo
In this example:
- We converted temperatures from Celsius to Fahrenheit using a dictionary comprehension.
- We categorized temperatures as "Cool", "Moderate", or "Warm" using a helper function.
- We used the
reduce()
function with a lambda to group cities by temperature category.
These techniques demonstrate how lambda functions can make complex dictionary operations more concise and readable. As you can see, combining lambda functions with Python's built-in functions and dictionary operations provides powerful tools for data manipulation.