-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathfaster_ordered_dict.py
56 lines (44 loc) · 1.51 KB
/
faster_ordered_dict.py
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from collections import deque
class FasterOrderedDict(dict):
"""
Faster than using the standard library class collections.OrderedDict,
because OrderedDict is pure Python. This class delegates every
operation to dict/deque, which are both C-based.
This handles only the operations that matter to the rest of Hydra and probably
won't work for other use cases without modification.
"""
def __init__(self):
dict.__init__(self)
self._elems = deque()
def __delitem__(self, key):
"""
slow but should be uncommon for our uses
"""
dict.__delitem__(self, key)
self._elems.remove(key)
def __setitem__(self, key, data):
if key in self:
dict.__setitem__(self, key, data)
else:
self._elems.append(key)
dict.__setitem__(self, key, data)
def __repr__(self):
elems = ', '.join(["'%s': %s" % (elem, self[elem])
for elem in self._elems])
return '{%s}' % elems
def __iter__(self):
return iter(self._elems)
def iteritems(self):
for elem in self._elems:
yield elem, self[elem]
def iterkeys(self):
return iter(self._elems)
def itervalues(self):
for elem in self._elems:
yield self[elem]
def keys(self):
return list(self._elems)
def values(self):
return [self[elem] for elem in self._elems]
def items(self):
return [(elem, self[elem]) for elem in self._elems]