Python's sort is stable: items with equal keys keep their original order
Look again at the two retries changes at 120. In the sort by time and in the sort by key and time, they stayed in arrival order: 5, then 3. That's a promise, not luck. Python's sort is stable: when several items have equal keys, they keep the order they had before the sort.
Now sort the log with no key at all:
for change in sorted(changes):
print(change)
('retries', 120, 3)
('retries', 120, 5)
('timeout', 100, 30)
('timeout', 160, 45)
('timeout', 220, 60)
With no key, the key is the whole tuple. When the name and the time tie, the value decides, so 3 now comes before 5.
A store that sorted this way would believe 5 was the later write. And with values that don't support <, it doesn't even run:
sorted([("limits", 5, {"cpu": 2}), ("limits", 5, {"cpu": 4})])
TypeError: '<' not supported between instances of 'dict' and 'dict'
Sort by the fields you mean, and let stability handle the ties. In the practice problem, two changes at the same time go to the one made later. A stable sort by time leaves the later one second.
reverse=True keeps the promise too. Items with equal keys still keep their original order. They are not flipped:
for change in sorted(changes, key=lambda c: c[1], reverse=True):
print(change)
('timeout', 220, 60)
('timeout', 160, 45)
('retries', 120, 5)
('retries', 120, 3)
('timeout', 100, 30)
Stability also lets you sort two fields in opposite directions when you can't negate one. Sort twice: first by the second field, then by the first. Pass reverse=True to the pass whose field goes the other way. The second sort keeps the first sort's order inside each group of equal keys. Here are the names from Z to A, with each name's changes oldest first:
by_time = sorted(changes, key=lambda c: c[1])
for change in sorted(by_time, key=lambda c: c[0], reverse=True):
print(change)
('timeout', 100, 30)
('timeout', 160, 45)
('timeout', 220, 60)
('retries', 120, 5)
('retries', 120, 3)
In the editor, write timelines(changes), with a sort that keeps ties in arrival order. It prints the log's timelines.