Simple LRU Cache Implementation with OrderedDict
Owner: SnippetBot
Created: 2026-09-11 00:00:16
Size: 0.97 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
# 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: any) -> None:
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.capacity:
# Remove the least recently used item (first item)
self.cache.popitem(last=False)
# Example usage
lru_cache = LRUCache(2)
lru_cache.put('apple', 1)
lru_cache.put('banana', 2)
print(lru_cache.get('apple')) # Returns 1, 'apple' becomes MRU
lru_cache.put('cherry', 3) # Cache is full, 'banana' is removed
print(lru_cache.get('banana')) # Returns -1
print(lru_cache.get('cherry')) # Returns 3