LFU Cache Evicts The Least Frequently Used

Track one OrderedDict bucket per use frequency and evict the oldest key at the lowest frequency, promoting keys on every get and put.

PythonData Integrity

Code

pythonsnippet
56 lines
from collections import OrderedDict, defaultdict


class LFUCache:
    """Evict the least frequently used key; oldest inserted wins ties."""

    def __init__(self, capacity: int) -> None:
        self.capacity = capacity
        self.values: dict = {}
        self.frequencies: defaultdict = defaultdict(int)
        self.keys_at: defaultdict = defaultdict(OrderedDict)
        self.lowest_frequency = 0

    def get(self, key):
        if key not in self.values:
            return None
        self._bump(key)
        return self.values[key]

    def put(self, key, value) -> None:
        if self.capacity <= 0:
            return
        if key in self.values:
            self.values[key] = value
            self._bump(key)
            return
        if len(self.values) >= self.capacity:
            self._evict_least_frequent()
        self.values[key] = value
        self.frequencies[key] = 0
        self.keys_at[0][key] = None
        self.lowest_frequency = 0

    def _bump(self, key) -> None:
        frequency = self.frequencies[key]
        del self.keys_at[frequency][key]
        self.keys_at[frequency + 1][key] = None
        self.frequencies[key] = frequency + 1
        if self.lowest_frequency == frequency and not self.keys_at[frequency]:
            self.lowest_frequency = frequency + 1

    def _evict_least_frequent(self) -> None:
        bucket = self.keys_at[self.lowest_frequency]
        victim, _ = bucket.popitem(last=False)
        del self.values[victim]
        del self.frequencies[victim]


cache = LFUCache(2)
cache.put("a", 1)
cache.put("b", 2)
cache.get("a")            # "a" is now used twice, "b" once
cache.put("c", 3)         # "b" is least frequent, evicted
print(cache.get("b"))     # None
print(cache.get("a"))     # 1
print(cache.get("c"))     # 3

Output

Captured from a sandboxed run of this snippet in the build pipeline.

None
1
3

Reading the program straight through

The moving parts are the class LFUCache and the functions __init__, get, put and _bump.

What to watch for

  • Every call in the file lands on a built-in API, so no package manager takes part.

Using it

Entry signature: def get(self, key)

get is what another module would consume; nothing else here is load-bearing for callers.

Key statements

def __init__(self, capacity: int) -> None:
    self.capacity = capacity
    self.values: dict = {}
    self.frequencies: defaultdict = defaultdict(int)
    self.keys_at: defaultdict = defaultdict(OrderedDict)
    self.lowest_frequency = 0
def _evict_least_frequent(self) -> None:
    bucket = self.keys_at[self.lowest_frequency]
    victim, _ = bucket.popitem(last=False)
    del self.values[victim]
    del self.frequencies[victim]
def _bump(self, key) -> None:
    frequency = self.frequencies[key]
    del self.keys_at[frequency][key]
    self.keys_at[frequency + 1][key] = None
    self.frequencies[key] = frequency + 1
    if self.lowest_frequency == frequency and not self.keys_at[frequency]:
        self.lowest_frequency = frequency + 1

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. The file defines `__init__`, `get`, `put` at load time.