Batu Lab NotesPractical developer guides

Move a recently used key to the end of OrderedDict

By Batu ยท English technical notes

Also published in our Blogger archive.

An OrderedDict can express recency directly: place the least recently used key at the beginning and the most recently used key at the end. move_to_end(key) moves an existing key to the rightmost position by default, without changing its value. In this recipe, reading "beta" from a three-entry cache marks it as recent, so the order changes from alpha, beta, gamma to alpha, gamma, beta.

popitem(last=False) then removes and returns the leftmost pair. That makes the eviction decision visible: ("alpha", 10) is discarded after beta was refreshed. The assertions verify both the updated ordering and the removed pair. A missing key is deliberately tested too; move_to_end("missing") raises KeyError rather than adding a new entry.

This is ordering logic, not a complete cache. The mapping does not compute values, enforce a capacity, expire stale entries, or synchronize concurrent access. A regular dict can move a key to its right end with d[key] = d.pop(key), but OrderedDict provides the dedicated operation and can efficiently move a key to either endpoint. Its equality with another OrderedDict is order-sensitive, which can matter in tests.

This article was drafted with AI assistance.

Source: Python OrderedDict.move_to_end() documentation

Example

from collections import OrderedDict

cache = OrderedDict([
    ("alpha", 10),
    ("beta", 20),
    ("gamma", 30),
])

recent_key = "beta"
assert cache[recent_key] == 20
cache.move_to_end(recent_key)
assert list(cache) == ["alpha", "gamma", "beta"]

evicted_key, evicted_value = cache.popitem(last=False)
assert (evicted_key, evicted_value) == ("alpha", 10)

try:
    cache.move_to_end("missing")
except KeyError:
    print("missing key rejected")

print(list(cache.items()))
print(f"evicted={evicted_key}:{evicted_value}")

Expected stdout

missing key rejected
[('gamma', 30), ('beta', 20)]
evicted=alpha:10