LRU-style caches
Maintain a bounded recent-items structure by moving accessed keys to one endpoint and evicting from the other.
Python · Class
OrderedDict is a dict subclass for mappings where changing entry order is important. It adds endpoint reordering and configurable-end removal operations beyond ordinary dictionary behavior.
OrderedDict is a dict subclass built for operations that rearrange key order. It retains insertion order, lets you move an existing key to either endpoint, and lets popitem choose whether removal occurs from the right or left.
class collections.OrderedDict([items])| Name | Type | Description |
|---|---|---|
iterable | iterable or mapping | Optional iterable or mapping supplying initial key-value pairs; the class constructor otherwise accepts the usual mapping-style inputs. |
last | bool | Whether to remove from the right endpoint (default) or the left endpoint. |
key | hashable | Existing key whose entry should be moved to an endpoint. |
An instance of a dict subclass with methods specialized for rearranging dictionary order.
from collections import OrderedDict
recent = OrderedDict([("a", 1), ("b", 2), ("c", 3)])
recent.move_to_end("a")
print(list(recent.items()))
print(recent.popitem(last=False))
print(list(recent.items()))Creates an ordered mapping, moves an existing key to the right endpoint, then removes the leftmost item.
Maintain a bounded recent-items structure by moving accessed keys to one endpoint and evicting from the other.
Repeatedly reposition entries while preserving mapping access and iteration behavior.
Consume entries from either endpoint with explicit FIFO or LIFO semantics.
OrderedDict is a dict subclass with methods specialized for rearranging dictionary order. It remains useful when frequent reordering matters, even though regular dict preserves insertion order.
Follow-up: Why is it suitable for an LRU cache? Its move_to_end() method efficiently moves accessed entries to an endpoint, and popitem(last=False) can evict the oldest entry.
popitem(last=True) removes and returns a key-value pair from the right side, giving LIFO behavior. With last=False, it removes from the left side, giving FIFO behavior.
Follow-up: How would you remove the oldest entry? Call popitem(last=False), because the leftmost item is the earliest ordered entry.
move_to_end(key, last=True) moves an existing key to the right endpoint by default. Passing last=False moves it to the beginning.
Follow-up: What happens if the key is absent? The operation cannot move a nonexistent key; normal key lookup behavior raises KeyError.
dictdefaultdictCounterUserDictmove_to_end()popitem()reversed()