Auto sort in Dictionaries???

Cliff Crawford cjc26 at
Mon Jul 23 22:07:10 EDT 2001

* Nick Perkins <nperkins7 at> menulis:
| class orderdict(dictionary):
|     """ dictionary which returns keys in the order of insertion """
|     def __init__(self):
|         dictionary.__init__(self)
|         self.n = 0
|     def __setitem__(self,key,value):
|         dictionary.__setitem__(self,(self.n,key),value)
|         self.n += 1
|     def __getitem__(self,key):
|         return dictionary.__getitem__(self,(self.n,key))

I don't think the above line will work...if you call __getitem__ on an
already-inserted key (not the last one inserted) then self.n will
already be incremented and you'll get a KeyError.

This is pretty clever, though..more clever than what I usually do, which
is append the keys to a list as they are inserted.  I think you can make
it work by doing the following instead:

    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 = dictionary.keys(self)
|         ks.sort()
|         return [ key for n,key in ks ]

This would have to be changed to:

    def keys(self):
        ks = [(n, key) for (key, (n, _)) in dictionary.items(self)]
        return [key for (n, key) in ks]

(A little too clever for my taste...:)

Cliff Crawford  
A sign should be posted over every campus toilet:
"This flush comes to you by courtesy of capitalism." 
                                 -- Camille Paglia

More information about the Python-list mailing list