LRU cache with OrderedDict in O(1) per operation
An LRU cache needs O(1) lookup, O(1) update, and O(1) eviction of the least recently used item. collections.OrderedDict is a natural fit: it preserves order and provides move_to_end(key) and popitem(last=False). On get, move the key to the end. On put, insert or update and move to the end; if over capacity, pop from the front. A plain dict plus a doubly linked list is the classic manual implementation, but OrderedDict encapsulates it. For function memoization, functools.lru_cache is usually the right tool.
Use OrderedDict when you need explicit LRU behavior with custom keys and values.
Use functools.lru_cache for pure functions; it is C-optimized and thread-safe for the cache structure.
Trade-off: an LRU cache adds memory and locking overhead. For high concurrency, sharding or a dedicated cache service may be better.
Common mistake: using a list and pop(0), which makes eviction O(n).
Version note: OrderedDict.move_to_end exists since Python 3.2; functools.lru_cache since 3.2 and has evolved with typed and user_function options.
0-2 years experience
2-5 years experience
5-8 years experience
8+ years experience