Created
May 12, 2014 09:56
-
-
Save glennzw/e4abb785fd2856d5b439 to your computer and use it in GitHub Desktop.
Python dict with max size constraint
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# [email protected] | |
from collections import OrderedDict | |
class fifoDict: | |
"""OrderedDict with FIFO size constraint""" | |
def __init__(self, size=1000, reducePc=0.2): | |
self.od = OrderedDict() | |
self.sz = size | |
self.reducePc=0.5 | |
def add(self, item): | |
if item not in self.od: | |
self.od[item] = 0 | |
def getNew(self): | |
newData = [] | |
markAsFetched = [] | |
for key, val in self.od.iteritems(): | |
if val == 0: | |
newData.append( key ) | |
for key in newData: | |
self.od[key] = 1 | |
#Reduce size of dict by reducePc % : | |
if len(self.od) > self.sz: | |
for i in range(int(self.reducePc * self.sz)): | |
try: | |
self.od.popitem(last = False) | |
except KeyError: | |
pass | |
return newData |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment