← Back to all snippets
PYTHON

Implement an LRU Cache with `collections.OrderedDict`

Discover how to build a simple Least Recently Used (LRU) cache in Python using `collections.OrderedDict`, crucial for optimizing performance in web applications.

from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity: int):
        self.cache = OrderedDict()
        self.capacity = capacity

    def get(self, key: str) -> any:
        if key not in self.cache:
            return -1 # Or raise KeyError, depending on desired behavior
        # Move the accessed item to the end (most recently used)
        value = self.cache.pop(key)
        self.cache[key] = value
        return value

    def put(self, key: str, value: any) -> None:
        if key in self.cache:
            self.cache.pop(key) # Remove existing item to update and move to end
        elif len(self.cache) >= self.capacity:
            # Remove the least recently used item (first item)
            self.cache.popitem(last=False)
        self.cache[key] = value

# Example usage:
lru_cache = LRUCache(capacity=3)

lru_cache.put("user:1", {"name": "Alice"})
lru_cache.put("product:A", {"price": 100})
lru_cache.put("order:X", {"status": "pending"})

print(f"Cache after initial puts: {list(lru_cache.cache.keys())}") # order: user:1, product:A, order:X

print(f"Get user:1: {lru_cache.get('user:1')}") # user:1 becomes most recently used
print(f"Cache after getting user:1: {list(lru_cache.cache.keys())}") # order: product:A, order:X, user:1

lru_cache.put("user:2", {"name": "Bob"}) # Cache is full, product:A (LRU) will be evicted
print(f"Cache after putting user:2: {list(lru_cache.cache.keys())}") # order: order:X, user:1, user:2

print(f"Get product:A (should be -1): {lru_cache.get('product:A')}")
How it works: This snippet demonstrates how to implement a basic Least Recently Used (LRU) cache using Python's `collections.OrderedDict`. `OrderedDict` maintains the order of item insertion, which is crucial for an LRU cache. When an item is accessed (`get`), it's moved to the end (most recently used). When a new item is added (`put`) and the cache is full, the least recently used item (the one at the beginning) is evicted using `popitem(last=False)`.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs