Code Snippets
/

OrderedDict Quirks Worth Knowing

OrderedDict Quirks Worth Knowing

Regular dicts have preserved insertion order since Python 3.7, so most modern code never reaches for `OrderedDict`. But OrderedDict still has a niche: it ships with `move_to_end` and `popitem(last=False)` methods that plain dicts do not, and its equality semantics differ from dict equality. This snippet covers the move-to-end LRU primitive, the order-sensitive equality, and when you should still pick OrderedDict in 2025.

Python
Medium
3 snippets
py-collections
py-standard-library
code-template
lru-cache

577 views

5

from collections import OrderedDict

cache = OrderedDict()
cache['a'] = 1
cache['b'] = 2
cache['c'] = 3

# Refresh 'a' as most-recently-used
cache.move_to_end('a')
print(list(cache))  # ['b', 'c', 'a']

# Promote 'b' to least-recently-used
cache.move_to_end('b', last=False)
print(list(cache))  # ['b', 'c', 'a']

# Pop the oldest (FIFO eviction in an LRU cache)
oldest = cache.popitem(last=False)
print(oldest)        # ('b', 2)
print(list(cache))   # ['c', 'a']

move_to_end(key) is the operation a hand-rolled LRU cache needs every time a key is read or written: bump it to the most-recently-used end. The companion popitem(last=False) evicts the least-recently-used entry in O(1). Plain dicts do not expose either method, which is the main reason OrderedDict still earns its keep in 2025. The same pair powers Python's functools.lru_cache under the hood.