forked from michaelliao/learn-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfifodict.py
More file actions
34 lines (26 loc) · 784 Bytes
/
fifodict.py
File metadata and controls
34 lines (26 loc) · 784 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import OrderedDict
class LastUpdatedOrderedDict(OrderedDict):
def __init__(self, capacity):
super(LastUpdatedOrderedDict, self).__init__()
self._capacity = capacity
def __setitem__(self, key, value):
containsKey = 1 if key in self else 0
if len(self) - containsKey >= self._capacity:
last = self.popitem(last=False)
print 'remove:', last
if containsKey:
del self[key]
print 'set:', (key, value)
else:
print 'add:', (key, value)
OrderedDict.__setitem__(self, key, value)
# test
d = LastUpdatedOrderedDict(capacity=3)
d['A'] = 100
d['B'] = 200
d['C'] = 300
d['D'] = 400
d['E'] = 500
print d