Skip to content

Instantly share code, notes, and snippets.

@maizy
Created April 15, 2014 08:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maizy/10713297 to your computer and use it in GitHub Desktop.
Save maizy/10713297 to your computer and use it in GitHub Desktop.
# _*_ coding: utf-8 _*_
from collections import OrderedDict
class LimitedDict(OrderedDict):
def __init__(self, limit):
super(LimitedDict, self).__init__()
self.limit = limit
def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
ret = super(LimitedDict, self).__setitem__(key, value, dict_setitem)
if len(self) > self.limit:
self.popitem(last=False)
return ret
if __name__ == '__main__':
a = LimitedDict(2)
a['a'] = 1
a['b'] = 2
print(repr(a)) # LimitedDict([('a', 1), ('b', 2)])
a['c'] = 3
print(repr(a)) # LimitedDict([('b', 2), ('c', 3)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment