Python Practice › Collections Programs › Program 15
LRU cache with OrderedDict
Write a small least-recently-used cache that holds 2 items.
Output
['a', 'c']
Approach
move_to_endon access;popitem(last=False)evicts the oldest.
Solution
from collections import OrderedDict class LRUCache: def __init__(self, capacity): self.capacity = capacity self.data = OrderedDict() def get(self, key): if key not in self.data: return None self.data.move_to_end(key) return self.data[key] def put(self, key, value): self.data[key] = value self.data.move_to_end(key) if len(self.data) > self.capacity: self.data.popitem(last=False) cache = LRUCache(2)cache.put("a", 1)cache.put("b", 2)cache.get("a")cache.put("c", 3)print(list(cache.data))Output
['a', 'c']
Line by line
Lines 22-24
Reading “a” makes it recently used, so adding “c” evicts “b”.
Learn the concept
New to this topic? Read the lesson, then come back.