Intermediate · 12 min
Sorting with keys
Sort richer data by the field that matters.
Choose a sort key
The key function returns the value Python should compare. sorted() creates a new list.
names = ["Mina", "Al", "Sofia"]
print(sorted(names, key=len))Output
['Al', 'Mina', 'Sofia']
Sort records
A lambda is a small unnamed function. Here it extracts each dictionary score for sorting.
players = [{"name": "Ada", "score": 8}, {"name": "Leo", "score": 12}]
ranked = sorted(players, key=lambda player: player["score"], reverse=True)
print(ranked[0]["name"])Output
Leo
Sorting with keys
- Read both sorting with keys examples before answering.
- Run the task, compare its exact output, and revise the code if needed.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Rank products
Sort products from highest to lowest price and display the product names in that order.
Use price as the key and reverse=True.