jemnotesversion 2 / featuring this entry or see all/search

Feb 11
This dictionary stores a limited number of entries, removing the oldest entries when it gets full. This could be used for a cache. Create a max-50-entry dictionary with f = FifoDict(50), for example.
class FifoDict(object):
    def __init__(self, maxentries=100):
        self.lastentries = []
        self.mydict = {}
        self.maxentries = maxentries

    def __getitem__(self, k):
        return self.mydict[k]

    def __setitem__(self, k, val):
        if len(self.lastentries) >= self.maxentries:
            del self.mydict[self.lastentries.pop()]
        self.mydict[k] = val
        self.lastentries.insert(0, k)

    def __str__(self):
        return str(self.mydict)

    def __repr__(self):
        return repr(self.mydict)