A key function picks what to compare, and a tuple key compares field by field
Here's a change log for a configuration store, in the order the changes arrived. Each entry is (key, time, value). To put it in time order, compare only the time:
changes = [
("timeout", 160, 45),
("retries", 120, 5),
("timeout", 100, 30),
# same time as the line above, arrived later
("retries", 120, 3),
("timeout", 220, 60),
]
for change in sorted(changes, key=lambda c: c[1]):
print(change)
('timeout', 100, 30)
('retries', 120, 5)
('retries', 120, 3)
('timeout', 160, 45)
('timeout', 220, 60)
A key function maps each item to the thing to compare. Here it's the time, c[1].
Python calls the key once per item, not once per comparison. A key that counted its calls confirmed it: 10,000 calls to sort 10,000 items.
For more than one field, return a tuple. By key, then time:
for change in sorted(changes, key=lambda c: (c[0], c[1])):
print(change)
('retries', 120, 5)
('retries', 120, 3)
('timeout', 100, 30)
('timeout', 160, 45)
('timeout', 220, 60)
Two tuples compare their first fields. They look at the second field only when the first fields tie:
| Compared | First fields | Then |
|---|---|---|
('retries', 120) and ('timeout', 100) | 'retries' is smaller | done |
('timeout', 100) and ('timeout', 160) | a tie | 100 < 160: done |
('retries', 120) and ('retries', 120) | a tie | a tie: equal keys |
The last row is two different changes with equal keys. The next section says which of them comes first.
To sort one field the other way, negate it when it's a number. Each key's newest change first is key=lambda c: (c[0], -c[1]), which puts timeout at 220, 160, 100. A string can't be negated. For a string, sort twice: the next step, on stable sorts, shows how.
In the editor, write newest_first(changes). It prints the log with the keys from A to Z, and each key's newest change first.