Build the LRU order from a dict and a doubly linked list
The fix is two structures working together. Start with the list.
Two sentinel nodes remove the special cases for an empty list and its ends
class Node:
def __init__(self, key=None, value=None):
self.key, self.value = key, value
self.prev = self.next = None
# sentinels: they hold no entry
head, tail = Node(), Node()
# an empty list
head.next, tail.prev = tail, head
nodes head.next is the oldest use, and tail.prev the newest. Each node points both ways.
A node holds a key, a value and two pointers: prev to the node before it, and next to the node after it. With both pointers, a node you're holding can be taken out in O(1), because both its neighbours are right there. A singly linked list can't do that: a node doesn't know who points at it.
head and tail are sentinels: dummy nodes that never hold an entry and never leave. So every real node always has a node on both sides, and there's no special case for an empty list, the first node or the last. The list is empty when head.next is tail.
The editor holds Node and an empty list between head and tail. Write is_empty(head, tail), and keys_oldest_first(head, tail), which walks from head.next to tail.