PYTHON
Sorting Lists of Dictionaries by Multiple Keys in Python
Master sorting complex data structures like lists of dictionaries in Python. Learn to sort by one or more keys, including handling ascending and descending orders, for better data organization.
import operator
data = [
{'name': 'Alice', 'age': 30, 'score': 95},
{'name': 'Bob', 'age': 24, 'score': 88},
{'name': 'Charlie', 'age': 30, 'score': 92},
{'name': 'David', 'age': 28, 'score': 95},
{'name': 'Eve', 'age': 24, 'score': 90},
]
print("Original Data:")
for item in data:
print(item)
# 1. Sort by a single key (e.g., 'age' ascending)
sorted_by_age = sorted(data, key=operator.itemgetter('age'))
print("
Sorted by Age (ascending):")
for item in sorted_by_age:
print(item)
# 2. Sort by multiple keys (e.g., 'age' ascending, then 'score' descending)
# The order of keys in itemgetter matters for primary and secondary sort.
# To reverse 'score', we use a lambda that negates the score.
sorted_by_age_score = sorted(data, key=lambda x: (x['age'], -x['score']))
print("
Sorted by Age (asc) then Score (desc):")
for item in sorted_by_age_score:
print(item)
# Alternative for multiple keys with operator.itemgetter and reverse
# This requires two passes or a more complex key if direct reversal of one field is needed.
# Simpler to use lambda for mixed ascending/descending on multiple keys.
# Example for multiple ascending:
sorted_by_age_name = sorted(data, key=operator.itemgetter('age', 'name'))
print("
Sorted by Age (asc) then Name (asc):")
for item in sorted_by_age_name:
print(item)
How it works: This snippet demonstrates how to sort a list of dictionaries, a common task in data manipulation. Python's `sorted()` function (or list's `sort()` method) accepts a `key` argument, which is a function that extracts a comparison key from each element in the list. For sorting by a single dictionary key, `operator.itemgetter()` is efficient and readable. For sorting by multiple keys (e.g., primary sort by 'age', then secondary sort by 'score'), a `lambda` function returning a tuple of keys is used. To achieve descending order for a numeric key within a multi-key sort, the value can be negated in the `lambda` function.