Auto sort in Dictionaries???
Nick Perkins
nperkins7 at home.com
Tue Jul 24 14:08:35 EDT 2001
"Cliff Crawford" <cjc26 at nospam.cornell.edu> wrote in message
news:iL477.106891
...
> I don't think the above line will work...
...
Quite right. My original code suffered from 4am syndrome.
Thanks for the help.
Here is the fixed up version:
class order_dict(dictionary):
"""Dictionary which returns contents in order of insertion"""
def __init__(self):
dictionary.__init__(self)
self.n = 0
def __setitem__(self, key, value):
dictionary.__setitem__(self, key, (self.n, value))
self.n += 1
def __getitem__(self, key):
return dictionary.__getitem__(self, key)[1]
def keys(self):
ks = [(n, key) for (key, (n, _)) in dictionary.items(self)]
ks.sort()
return [key for (n, key) in ks]
def values(self):
vals = dictionary.values(self)
vals.sort()
return [ value for (n,value) in vals ]
def items(self):
return [(key, self.__getitem__(key)) for key in self.keys()]
More information about the Python-list
mailing list