Sorting With a Key Function

A key function maps each item to the value the sort should use in comparisons. Keep it consistent with what the result is meant to show.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Choose the converted key
  2. Design secondary order directly
  3. Read the key separately from the original record
  4. Resolve missing values before comparing keys

Choose the converted key

Text rows with fields "2" and "11" sort differently as labels and as quantities. Python can supply a key extracting and parsing the numeric field first. The lexicographic and numeric comparison rules explain the reversal.

Design secondary order directly

A key tuple can hold numeric priority first and name second. That picks alphabetical order for equal priorities. If source order among equal priorities matters, use stable ordering and compare only the priority.[1]

Read the key separately from the original record

A schedule has records ("A", 40), ("B", 15) and ("C", 15), with the second item a duration in minutes. Sorting on duration moves the complete records to B, C, A while preserving the original order of the fifteen-minute ties in Python. Returning the first field from the key function sorts by name instead. Check the list of computed keys independently when the output surprises you. See stable ordering.

Resolve missing values before comparing keys

A key that returns integers for known durations and None for unknown ones gives incomparable sorts in Python. A tuple key can distinguish “unknown” from “known” first and compare the numeric field only within the latter group. A final unique ID can make order deterministic across independently assembled inputs. Test a missing duration, zero minutes and a genuine tie together. See missing values and sentinels.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩