forcing dictionary order
Steven D. Majewski
sdm7g at Virginia.EDU
Thu Mar 29 14:04:45 EST 2001
On Thu, 29 Mar 2001, Bob van der Poel wrote:
>
> I'd like (not a must!) to walk a dictionary in the same order in which
> it was created. Example:
>
> foo={ key1: (), key2: (), key3: () }
>
> If I do:
>
> for a in foo.keys(): ...
>
> the order is not "key1, key2, key3", which is what I want. Note, I can't
> do something simple like sort() on the keys since the are not in any
> alphanumeric order. I'm just using this to generate a largish table for
> another program, and the actual order doesn't matter for it to work
> properly, but it would nicer if it were in the correct logical order.
> So, I'm not going to spend a lot of time on this, but if there is a
> simple way????
Once they are in the dictionary, they keys are hashed, so any info
on the order of insertion is lost.
You can create a Class based on UserDict, and override the __setitem__
method (and to be consistent, __delitem__ and update) to keep an ordered
list of keys in parallel.
You might also redefine popitem to return pairs in the proper order.
( Do you want FIFO or LIFO ? )
-- Steve Majewski
More information about the Python-list
mailing list