← retour aux snippets

collections.OrderedDict: move_to_end pour LRU

Gérer un cache LRU simple avec move_to_end(last=True).

python collections #cache

objectif

Gérer un cache LRU simple avec move_to_end(last=True).

code minimal

from collections import OrderedDict
od = OrderedDict()
for k in ["a","b","c"]: od[k] = k
od.move_to_end("a")  # 'a' devient le plus récent
print(list(od.keys()) == ["b","c","a"])  # attendu: True

utilisation

from collections import OrderedDict
cache = OrderedDict()
def put(k,v):
    cache[k]=v; cache.move_to_end(k);
    if len(cache)>2: cache.popitem(last=False)
for i in range(3): put(i,i)
print(list(cache.keys()) == [1,2])

variante(s) utile(s)

from collections import OrderedDict
print(hasattr(OrderedDict(), "move_to_end"))

notes

  • Depuis 3.7, dict préserve l’ordre d’insertion mais pas move_to_end.
  • Pour des LRU robustes, voyez functools.lru_cache.