Python
Python

Implement a LRU Cache Without Using functools.lru_cache

December 3, 2025

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 ?

Ready to leverage the power of conversational AI? Start your project with Zignuts expert AI developers.
bg-image
download-image
Company Deck
PDF, 3MB
© 2026 Zignuts Technolab. All Rights Reserved.
branch imagesbranch imagesbranch imagesbranch imagesbranch imagesbranch images