0
|
1 """
|
|
2 Ordered dictionary implementation.
|
|
3 """
|
|
4
|
|
5 from UserDict import UserDict
|
|
6
|
|
7 class odict(UserDict):
|
|
8 """
|
|
9 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747
|
|
10
|
|
11 This dictionary class extends UserDict to record the order in which items are
|
|
12 added. Calling keys(), values(), items(), etc. will return results in this
|
|
13 order.
|
|
14 """
|
|
15 def __init__( self, dict = None ):
|
|
16 self._keys = []
|
|
17 UserDict.__init__( self, dict )
|
|
18
|
|
19 def __delitem__( self, key ):
|
|
20 UserDict.__delitem__( self, key )
|
|
21 self._keys.remove( key )
|
|
22
|
|
23 def __setitem__( self, key, item ):
|
|
24 UserDict.__setitem__( self, key, item )
|
|
25 if key not in self._keys:
|
|
26 self._keys.append( key )
|
|
27
|
|
28 def clear( self ):
|
|
29 UserDict.clear( self )
|
|
30 self._keys = []
|
|
31
|
|
32 def copy(self):
|
|
33 new = odict()
|
|
34 new.update( self )
|
|
35 return new
|
|
36
|
|
37 def items( self ):
|
|
38 return zip( self._keys, self.values() )
|
|
39
|
|
40 def keys( self ):
|
|
41 return self._keys[:]
|
|
42
|
|
43 def popitem( self ):
|
|
44 try:
|
|
45 key = self._keys[-1]
|
|
46 except IndexError:
|
|
47 raise KeyError( 'dictionary is empty' )
|
|
48 val = self[ key ]
|
|
49 del self[ key ]
|
|
50 return ( key, val )
|
|
51
|
|
52 def setdefault( self, key, failobj=None ):
|
|
53 if key not in self._keys:
|
|
54 self._keys.append( key )
|
|
55 return UserDict.setdefault( self, key, failobj )
|
|
56
|
|
57 def update( self, dict ):
|
|
58 for ( key, val ) in dict.items():
|
|
59 self.__setitem__( key, val )
|
|
60
|
|
61 def values( self ):
|
|
62 return map( self.get, self._keys )
|
|
63
|
|
64 def iterkeys( self ):
|
|
65 return iter( self._keys )
|
|
66
|
|
67 def itervalues( self ):
|
|
68 for key in self._keys:
|
|
69 yield self.get( key )
|
|
70
|
|
71 def iteritems( self ):
|
|
72 for key in self._keys:
|
|
73 yield key, self.get( key )
|
|
74
|
|
75 def __iter__( self ):
|
|
76 for key in self._keys:
|
|
77 yield key
|
|
78
|
|
79 def reverse( self ):
|
|
80 self._keys.reverse()
|
|
81
|
|
82 def insert( self, index, key, item ):
|
|
83 if key not in self._keys:
|
|
84 self._keys.insert( index, key )
|
|
85 UserDict.__setitem__( self, key, item )
|