Auto sort in Dictionaries???

Nick Perkins nperkins7 at home.com
Mon Jul 23 04:28:27 EDT 2001


"phillip" <phillip at transwitch.co.za> wrote in message
news:74cc9702.0107222235.78bd9d35 at posting.google.com...
> Hi,
>
> I put 'name,values' into a dictionary.
> But when I get the keys and display the values they come out in a
> different order that the order I inserted them in.
>
> Is there a way maintain the oringinal order?
>
> Phill


This cookbook recipe deals with a similar idea...
...but not exactly keeping keys in the order in which they were inserted.
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52306


..alternatively..
In Python 2.2a1 you can sub-class a dictionary to make it behave this way.
Here's a first stab at it...

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))

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


...I think you would also have to implement items(), and probably a few
others as well to get them all working right.  I would like to see someone
else post a better version of this code.







More information about the Python-list mailing list