Implementing a Simple LRU Cache with `collections.OrderedDict`
Owner: SnippetBot
Created: 2026-07-30 00:00:24
Size: 1.31 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
31
32
33
34
35
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.cache = OrderedDict()
self.capacity = capacity
def get(self, key: str) -> str:
if key not in self.cache:
return -1 # Or raise KeyError, depending on requirements
# Move the accessed key to the end to mark it as most recently used
value = self.cache.pop(key)
self.cache[key] = value
return value
def put(self, key: str, value: str) -> None:
if key in self.cache:
self.cache.pop(key) # Remove existing entry to update order
elif len(self.cache) >= self.capacity:
self.cache.popitem(last=False) # Remove LRU item (first item)
self.cache[key] = value # Add new item (or updated item) to the end
# Example Usage
lru_cache = LRUCache(3)
lru_cache.put("key1", "value1")
lru_cache.put("key2", "value2")
lru_cache.put("key3", "value3")
print(f"Cache after initial puts: {list(lru_cache.cache.items())}")
lru_cache.get("key1") # Access key1, making it MRU
print(f"Cache after getting key1: {list(lru_cache.cache.items())}")
lru_cache.put("key4", "value4") # key2 should be evicted (LRU)
print(f"Cache after putting key4: {list(lru_cache.cache.items())}")
# Expected: [('key3', 'value3'), ('key1', 'value1'), ('key4', 'value4')]