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

221 views

5

from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity):
        if capacity <= 0:
            raise ValueError('capacity must be positive')
        self.capacity = capacity
        self.store = OrderedDict()

    def get(self, key):
        if key not in self.store:
            return None
        self.store.move_to_end(key)         # mark recently used
        return self.store[key]

    def put(self, key, value):
        if key in self.store:
            self.store.move_to_end(key)
        self.store[key] = value
        if len(self.store) > self.capacity:
            self.store.popitem(last=False)  # evict the LRU front entry

    def __repr__(self):
        return f'LRUCache({list(self.store.items())})'

cache = LRUCache(capacity=3)
cache.put('a', 1)
cache.put('b', 2)
cache.put('c', 3)
print(cache)        # LRUCache([('a', 1), ('b', 2), ('c', 3)])

cache.get('a')      # touch 'a'; now 'b' is the LRU.
cache.put('d', 4)   # evicts 'b'.
print(cache)        # LRUCache([('c', 3), ('a', 1), ('d', 4)])

print(cache.get('b'))  # None (evicted)
print(cache.get('a'))  # 1

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.