Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need python dictionary to act like deque (have maximum length)

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.

like image 556
Yngve Moe Avatar asked Mar 14 '18 09:03

Yngve Moe


2 Answers

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)
like image 134
Sraw Avatar answered Oct 21 '22 07:10

Sraw


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.

like image 27
Alex Hall Avatar answered Oct 21 '22 08:10

Alex Hall