Python Sorting With a Key
A key is a small rule that tells sorted() how to order items. The key turns each item into its sort value first.
Sort words by length
key=len turns each word into its length. Python sorts the lengths, not the letters.
words = ["pear", "fig", "banana", "kiwi"]
print(sorted(words, key=len))Sort names fairly
key=str.lower sorts by the lower-case forms. Capitals then lose their head start.
names = ["cherry", "Banana", "apple"]
print(sorted(names, key=str.lower))Sort dicts by one field
A lambda picks the score out of each dict. Python sorts by the scores.
players = [{"name": "Ada", "score": 88}, {"name": "Bob", "score": 95}, {"name": "Cy", "score": 71}]
print(sorted(players, key=lambda p: p["score"]))Biggest first
reverse=True flips the order. The highest score comes first now.
players = [{"name": "Ada", "score": 88}, {"name": "Bob", "score": 95}, {"name": "Cy", "score": 71}]
best = sorted(players, key=lambda p: p["score"], reverse=True)
print(best[0]["name"])
print(best[0]["score"])Example
players = [
{"name": "Ada", "score": 88},
{"name": "Bob", "score": 95},
{"name": "Cy", "score": 71},
{"name": "Dee", "score": 95},
]
ranked = sorted(players, key=lambda p: p["score"], reverse=True)
for place, player in enumerate(ranked, start=1):
print(place, player["name"], player["score"])Key points
- Key: the rule that sets the order while sorting
- Use key= inside sorted() or sort() to choose the rule
- Use key=len to sort words by length
- Use key=str.lower for a fair text sort
- Use a lambda as the key to sort by one part of each item
- Python calls the key once for each item, then sorts the results.
- Use reverse=True with a key to sort from big to small
- The key never changes the items. It only changes their order.
In this example, the list holds four players with scores. sorted() with key=lambda p: p["score"] sorts by the score field. reverse=True puts the highest score first. enumerate() counts the places from 1. The printout is the leaderboard, and the order proves the key worked: Bob and Dee share 95 at the top, then Ada with 88, then Cy with 71.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does key=len do in sorted(words, key=len)?