Python Snippet

LRU Cache via OrderedDict

Difficulty: Medium

An LRU (least-recently-used) cache evicts whichever entry has been untouched the longest when it hits its capacity. `collections.OrderedDict` makes the implementation tiny: `move_to_end` keeps the most-recently-used key at the back, and `popitem(last=False)` evicts the front. This entry covers the get/put loop, the `@functools.lru_cache` shortcut, and a mini benchmark.

Code Snippets
/

LRU Cache via OrderedDict

LRU Cache via OrderedDict

An LRU (least-recently-used) cache evicts whichever entry has been untouched the longest when it hits its capacity. `collections.OrderedDict` makes the implementation tiny: `move_to_end` keeps the most-recently-used key at the back, and `popitem(last=False)` evicts the front. This entry covers the get/put loop, the `@functools.lru_cache` shortcut, and a mini benchmark.

Python
Medium
3 snippets
lru-cache
data-structures
py-collections
py-standard-library

219 views

5

OrderedDict keeps insertion order AND lets you mutate that order in O(1). move_to_end(key) lifts a key to the back of the dict; popitem(last=False) removes the front item. Together they implement LRU semantics: every get and successful put lifts its key, and any put that pushes past capacity removes the least-recently-touched front entry. Because both operations are O(1), the cache scales: 100K entries with 1M operations stays well under a second.