Evict Least Recently Used Entries
Core idea
An LRU cache keeps recently accessed keys and evicts the least recently used one when a positive capacity is exceeded. Combine lookup and recency order with OrderedDict: move_to_end marks a hit or update as newest; popitem(last=False) removes the oldest. A cache miss does not change recency in this example. For typical hash distribution, these operations are expected O(1).
from collections import OrderedDictcache = OrderedDict([('A',10),('B',20)])print(cache['A'])cache.move_to_end('A')cache['C'] = 30print(cache.popitem(last=False))print(list(cache))Reading A and explicitly refreshing it makes B the eviction victim.
Update an existing entry
from collections import OrderedDictcache = OrderedDict([('x',1),('y',2)])cache['x'] = 9cache.move_to_end('x')print(list(cache.items()))Updating the value alone is not the same as updating recency.
Common mistake
Define capacity zero, misses, update semantics and concurrency separately. This small cache is not a thread-safe replacement for a production cache.
Practice
Implement get and put methods for capacity two, refreshing on hits and updates. Trace repeated hits, misses and eviction.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
LRU cache
Check your understanding of lru cache.
What is printed?
from collections import OrderedDictc=OrderedDict.fromkeys(['a','b','c']);c.move_to_end('a')print(list(c))What is printed?
from collections import OrderedDictc=OrderedDict([('a',1),('b',2)])print(c.popitem(last=False))What does a hit do under LRU?
What triggers eviction in this design?