Is there any builtin (or very simple) method of having a python dictionary work in a similar fashion as deque.
I need it to have a maximum size, and when new keys are added, if the maximum length is reached then the key added first is deleted. It shouldn't be too difficult to implement as a custom class, but using builtins is always prefered.
I am using Python 3.6 if that is of any help.
It sounds like a variant of OrderedDict
.
class FixSizeOrderedDict(OrderedDict):
def __init__(self, *args, max=0, **kwargs):
self._max = max
super().__init__(*args, **kwargs)
def __setitem__(self, key, value):
OrderedDict.__setitem__(self, key, value)
if self._max > 0:
if len(self) > self._max:
self.popitem(False)
It sounds like you want a least recently used (LRU) cache.
The functools.lru_cache decorator might be useful to you. If you want more control, then check out the package pylru or just google Python LRU cache.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With