Skip to content

Instantly share code, notes, and snippets.

@bityob
Created December 25, 2017 19:09
Show Gist options
  • Save bityob/9edfdfb73b7bdf192a8968e1260463f8 to your computer and use it in GitHub Desktop.
Save bityob/9edfdfb73b7bdf192a8968e1260463f8 to your computer and use it in GitHub Desktop.
Dictionary with maximun length, keep last N keys on dictionary, using deque object
from collections import deque
class DictWithMaxKeys:
def __init__(self, maxlen, init=None):
self.maxlen = maxlen
self._deque = deque()
self._dict = {}
if init is not None:
self._dict.update(init)
def __getitem__(self, key):
return self._dict[key]
def __setitem__(self, key, value):
# If key not in dictionary, we have to check did maxlen value exeeded,
# and remove the last element from deque, before adding the key
if key not in self._dict:
if len(self._deque) >= self.maxlen:
last_key = self._deque.popleft()
del self._dict[last_key]
self._deque.append(key)
self._dict[key] = value
def __delitem__(self, key):
del self._dict[key]
def __contains__(self, key):
return key in self._dict
def __len__(self):
return len(self._dict)
def __repr__(self):
return repr(self._dict)
if __name__ == '__main__':
# Simple test
d = DictWithMaxKeys(5)
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4
d['e'] = 5
d['f'] = 6
print(d._dict)
# Test with all abc letters
from string import ascii_letters
e = DictWithMaxKeys(maxlen=5)
print(e._dict)
for i, letter in enumerate(ascii_letters):
e[letter] = i
print(e._dict)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment