1 """
2 KeyedList sorted dictionary class.
3
4 $Id: keyedlist.py 7629 2008-01-16 16:13:21Z jbednar $
5 """
6 __version__='$Revision: 7629 $'
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
26 """
27 Extends the built-in type 'list' to support dictionary-like
28 access using []. The internal representation is as an ordinary
29 list of (key,value) pairs, not a hash table like an ordinary
30 dictionary, so that the elements will remain ordered.
31
32 Note: Not all list operations will work as expected, because
33 [] does not return the name tuple.
34
35 Redefined functions::
36
37 __getitem__ ([,])
38 __setitem__ ([,])
39 append -- Now takes a tuple (key,value) so that value
40 can be later accessed by [key].
41
42 New functions modeled from dictionaries::
43
44 get
45 set
46 has_key
47 keys
48 items
49 update
50
51 Key values are not allowed to be None, because None is a
52 default return value for get() when there is no object
53 by that name.
54 """
55
57 """The bracket [] accessor."""
58 for (name,value) in self:
59 if name == key:
60 return value
61
62
63
64 if isinstance(key,int):
65 for (index,(name,value)) in enumerate(self):
66 if index == key:
67 return value
68
69 raise KeyError(key)
70
71
73 """
74 The bracket [] mutator.
75 Overwrite value if key already exists, otherwise append.
76 """
77 return self.set(k,v)
78
79
80 - def append(self, (key, value)):
81 """
82 Append a new object to the end of the existing list.
83
84 Accepts a 2-tuple (key, value).
85
86 Strictly speaking, this operation did not need to be redefined
87 in this subclass, but by forcing the tuple in the function
88 parameters, we may be able to catch an erroneous assignment.
89 """
90 super(KeyedList,self).append(tuple((key,value)))
91
92
93 - def get(self, key, default=None):
94 """
95 Get the value with the specified key.
96
97 Returns None if no value with that key exists.
98 """
99 for (name,value) in self:
100 if name == key:
101 return value
102
103 return default
104
105
106 - def set(self, key, value):
107 """
108 If the key already exists in the list, change the entry.
109 Otherwise append the new (key,value) to the end of the list.
110 """
111 for (k,v) in self:
112 if k == key:
113 i = self.index((k,v))
114 self.pop(i)
115 self.insert(i,(key, value))
116 return True
117 self.append((key, value))
118 return True
119
120
122 """Return True iff key is found in the ordered list."""
123 for (name,value) in self:
124 if name == key:
125 return True
126 return False
127
128
130 """
131 Provide the item function supported by dictionaries.
132 A keyed list already is stored in this format, so just returns
133 the actual underlying list.
134 """
135 return list(self)
136
137
139 """A copy of the list of keys."""
140 return [k for (k,v) in self.items()]
141
142
144 """A copy of the list of values."""
145 return [v for (k,v) in self.items()]
146
147
149 """Updates (and overwrites) key/value pairs from b."""
150 for (k,v) in b.items():
151 self.set(k,v)
152