4/30
Part 1 of 7 · Score orderLearn and do

Store the key, not the title

From here on, the lesson stores keys instead of bare titles. A key is the tuple (-score, title):

keys = sorted((-score, title) for title, score in CATALOG.items())
print(keys)
print(min(keys))
[(-9, 'Comet'), (-7, 'Harbor'), (-7, 'Maple'), (-5, 'Orbit'), (-3, 'Tundra')]
(-9, 'Comet')

Three things make keys better than titles:

  • A key sorts without the dict. sorted(keys) needs no key= function, because the tuple already holds everything the order depends on. Sorted lists and heaps compare keys directly, and both come later in this lesson.
  • The smallest key is the best title. min(keys) is the title to show next, and keys[0] is the same thing once the list is sorted.
  • No two keys are ever equal. Titles are unique, so the title ends every tie. Python's heapq notes warn that a tuple compare breaks when two priorities are equal and the items after them can't be compared. Here the item after the score is a string, which always compares.

The cost of a key is that it goes stale. When a score changes, the old key is still sitting in whatever list holds it. Part 3 is about exactly that.

The editor holds key and best. Write key(title, score) to build the tuple, and best(scores) to return the title whose key is smallest.