Sort list by multiple keys with tuple ordering in Python
Sort a list of dictionaries by multiple criteria — surname, age, then score descending — using a tuple key and negation.
Python code
24 linesdef sort_multi_key(data):
# Sorts by surname, then age, then score descending
return sorted(
data,
key=lambda person: (
person['surname'].lower(),
person['age'],
-person['score'] # negative to reverse sort by score
)
)
if __name__ == "__main__":
people = [
{'surname': 'Smith', 'age': 30, 'score': 88},
{'surname': 'Smith', 'age': 30, 'score': 95},
{'surname': 'Smith', 'age': 25, 'score': 78},
{'surname': 'Jane', 'age': 30, 'score': 91},
{'surname': 'Doe', 'age': 25, 'score': 85},
]
sorted_people = sort_multi_key(people)
for p in sorted_people:
print(f"{p['surname']}, {p['age']}, {p['score']}")
Output
Doe, 25, 85
Jane, 30, 91
Smith, 25, 78
Smith, 30, 88
Smith, 30, 95
How it works
sorted() evaluates the key function once per item and sorts by the natural comparison of the returned tuple. Tuples compare element-by-element: Python moves to the next element only when the current ones are equal. Lowercasing the surname normalizes case-sensitive ordering. Negating the score inverts the order for that field, giving descending sort while the others stay ascending. This pattern keeps all sorting logic in one readable lambda, avoiding multiple passes.
Common mistakes
- Forgetting to lowercase strings, causing case-sensitive order
- Negating numeric fields you want ascending, inverting the order
- Assuming `sorted` mutates the original list — it returns a new list
- Using `reverse=True` to sort score descending, which also reverses every other field
Variations
- Use `operator.itemgetter` for a faster key when you don't need case normalization or negation
- Chain multiple sorts: sort by score descending first, then by age and surname for stability
Real-world use cases
- Ranking products by category, stock, and price priority in an e‑commerce dashboard
- Sorting employee directories by department, tenure, and salary for reporting
- Ordering tournament standings by points, goal difference, and goals scored
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.