#Python tip: Regular dicts can efficiently emulate methods ex | Nikita Shpilevoy | About IT, AI, etc
#Python tip:
Regular dicts can efficiently emulate methods exclusive to OrderedDict:
# Remove oldest
# od.popitem(0)
>>> d = dict(a=1, b=2, c=3)
>>> del d[next(iter(d))]
>>> d
{'b': 2, 'c': 3}
# Refresh position
# od.move_to_end('b')
>>> d['b'] = d.pop('b')
>>> d
{'c':3, 'b': 2}
These two methods are all you need to efficiently implement your own LRU cache variants:
# Cache miss: Store new entry and remove oldest
d[args] = func(*args)
if len(d) > maxsize:
d.popitem(0)
# Cache hit: Refresh position
d.move_to_end(args)
https://docs.python.org/3/library/collections.html#ordereddict-examples-and-recipes
Regular dicts already have d.popitem() which does the same as od.popitem(True) for OrderedDicts.
Ordered dicts have an od.move_to_end(key, 0) that moves entries to the beginning. There is no fast, clean equivalent for regular dicts.