LOGBOOK

HELP

Quiz Entry - updated: 2026.11.27

How do you sort records in Python by several keys, say by department and within each department by salary, using only single-key sorts?

Sort by the least important key first and by the most important key last: staff.sort(key=salary), then staff.sort(key=department). Python's sort is stable, so the second sort keeps the salary order within each department. This is lexicographic sort, with Python's own stable sort for every pass.

staff.sort(key=lambda p: p.salary)       # secondary key first
staff.sort(key=lambda p: p.department)   # primary key last

It is the same backwards order as in lexicographic sort, for the same reason: the last sort decides, and stability keeps the earlier order among ties. Python's documentation recommends this technique for complex sorts, and it also allows mixing directions, for example reverse=True on one of the passes only.

Two other routes to the same result: one sort with a tuple as key, staff.sort(key=lambda p: (p.department, p.salary)), since Python compares tuples lexicographically; or, in Java, one comparator built with Comparator.comparing(Person::department).thenComparing(Person::salary).

Go deeper:

From Quiz: ADS / Sorting Lower Bound, Bucket-Sort and Radix-Sort | Updated: Nov 27, 2026