PYTHON

Implement an LRU Cache for Web Performance

Optimize web application performance by caching frequently accessed data using a Least Recently Used (LRU) strategy with Python's collections.OrderedDict for efficient key management.

from collections import OrderedDict

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

    def get(self, key: str) -> str:
        if key not in self.cache:
            return -1
        # Move the accessed item to the end (most recently used)
        self.cache.move_to_end(key)
        return self.cache[key]

    def put(self, key: str, value: str) -> None:
        if key in self.cache:
            self.cache.move_to_end(key)
        self.cache[key] = value
        if len(self.cache) > self.capacity:
            # Remove the first item (least recently used)
            self.cache.popitem(last=False)

# Example Usage:
lru_cache = LRUCache(2)
lru_cache.put("page1", "Content of Page 1")
lru_cache.put("page2", "Content of Page 2")
print(lru_cache.get("page1")) # Output: Content of Page 1 (page1 is now most recently used)
lru_cache.put("page3", "Content of Page 3") # page2 is evicted
print(lru_cache.get("page2")) # Output: -1 (page2 was evicted)
print(lru_cache.get("page3")) # Output: Content of Page 3
How it works: This snippet demonstrates how to build a Least Recently Used (LRU) cache using Python's `collections.OrderedDict`. An LRU cache is essential for web applications to store frequently accessed data, reducing database load and improving response times. `OrderedDict` maintains insertion order, allowing us to easily identify and remove the least recently used item (the first item) and move the most recently used items to the end. The `get` method moves an accessed item to the end, while the `put` method adds or updates an item, evicting the oldest if the cache capacity is exceeded.

Need help integrating this into your project?

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

Hire DigitalCodeLabs