Python Snippet

OrderedDict Quirks Worth Knowing

Difficulty: Medium

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.

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

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.