This is a pretty good space. What you need are two structures. You need to tell you something that your key ( hash in your case) is known to the collection. For this, the dict very suitable; we just match hash to timestamp so you can easily find each item. Iterating over elements in order of time is a task especially suitable for Heaps, which are provided by the heapq module. Each time we see a key, we simply add it to our heap, like a tuple (timestamp, hash) .
Unfortunately, there is no way to look at a list with inheritance and delete certain items (because, say, they were updated before the expiration date). We will get around this by simply ignoring the heap entries that have timestamps that differ from the value in the dict.
So, here is a place to start, perhaps you can add methods to the wrapper class to support additional operations or change the way data is stored:
import heapq class ExpiringCache(object): def __init__(self): self._dict = {} self._heap = [] def add(self, key, expiry): self._dict[key] = expiry heapq.heappush(self._heap, (expiry, key)) def contains(self, key): return key in self._dict def collect(self, maxage): while self._heap and self._heap[0][0] <= maxage: expiry, key = heapq.heappop(self._heap) if self._dict.get(key) == expiry: del self._dict[key] def items(self): return self._dict.items()
create cache and add some elements
>>> xc = ExpiringCache() >>> xc.add('apples', 1) >>> xc.add('bananas', 2) >>> xc.add('mangoes', 3)
re-add an item with an even later expiration
>>> xc.add('apples', 4)
collect all "older" than two time blocks
>>> xc.collect(2) >>> xc.contains('apples') True >>> xc.contains('bananas') False