LRU cache with OrderedDict

MediumCollections Programs · 15 of 20

Write a small least-recently-used cache that holds 2 items.

Advertisement
Output
['a', 'c']

Approach

  1. move_to_end on access; popitem(last=False) evicts the oldest.

Solution

Python
from collections import OrderedDict class LRUCache:    def __init__(self, capacity):        self.capacity = capacity        self.data = OrderedDict()     def get(self, key):        if key not in self.data:            return None        self.data.move_to_end(key)        return self.data[key]     def put(self, key, value):        self.data[key] = value        self.data.move_to_end(key)        if len(self.data) > self.capacity:            self.data.popitem(last=False) cache = LRUCache(2)cache.put("a", 1)cache.put("b", 2)cache.get("a")cache.put("c", 3)print(list(cache.data))
Output
['a', 'c']

Line by line

Lines 22-24

Reading “a” makes it recently used, so adding “c” evicts “b”.

Learn the concept

New to this topic? Read the lesson, then come back.

More collections programs

← All 20 Collections Programs

Leave a Comment