TIL - Python's operator.itemgetter Makes Multi-Key Sorting Fast and Expression-Free
Lambda-based sort keys are fine for one field, but operator.itemgetter is faster (no Python frame overhead) and cleaner when sorting by multiple keys on dicts or tuples.
from operator import itemgetter
records = [
{"name": "Alice", "dept": "Eng", "salary": 90000},
{"name": "Bob", "dept": "Eng", "salary": 85000},
{"name": "Carol", "dept": "HR", "salary": 72000},
{"name": "Dave", "dept": "HR", "salary": 80000},
]
# Sort by dept ascending, then salary descending
by_dept = sorted(records, key=itemgetter("dept"))
# For descending salary within dept, sort in two passes (stable sort)
by_dept_salary = sorted(
sorted(records, key=itemgetter("salary"), reverse=True),
key=itemgetter("dept")
)
print([(r["name"], r["dept"], r["salary"]) for r in by_dept_salary])
# [('Alice', 'Eng', 90000), ('Bob', 'Eng', 85000),
# ('Dave', 'HR', 80000), ('Carol', 'HR', 72000)]
# Works on tuples too
rows = [(1, "z"), (2, "a"), (1, "a")]
print(sorted(rows, key=itemgetter(0, 1)))
# [(1, 'a'), (1, 'z'), (2, 'a')]itemgetter(0, 1) returns a tuple of values — Python's tuple comparison handles tie-breaking automatically.