Python

Implement a LRU Cache Without Using functools.lru_cache

December 3, 2025

download ready
Thank You
Your submission has been received.
We will be in touch and contact you soon!

An LRU Cache gets rid of the stuff you haven't used in a while when it's full. An OrderedDict helps keep track of what's been used and quickly kicks out old stuff. This way, getting to stuff and getting rid of stuff is super fast.

The LRU Cache keeps things in an OrderedDict to keep track of what's used. When you add or get something, it goes to the end of the line to show it's been used recently. If it's too full, the oldest thing at the beginning gets the boot.

Code

from collections import OrderedDict

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

    def get(self, key):
        if key not in self.cache: return -1
        self.cache.move_to_end(key)
        return self.cache[key]

    def put(self, key, val):
        self.cache[key] = val
        self.cache.move_to_end(key)
        if len(self.cache) > self.capacity:
            self.cache.popitem(last=False)
Hire Now!

Need Help with Python Development ?

Work with our skilled python developers to accelerate your project and boost its performance.
**Hire now**Hire Now**Hire Now**Hire now**Hire now