forcing dictionary order

Remco Gerlich scarblac at pino.selwerd.nl
Fri Mar 30 08:37:12 CEST 2001


Bob van der Poel <bvdpoel at uniserve.com> wrote in comp.lang.python: 
> 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????

Dictionaries by themselves don't do this, they don't have any particular
order at all, and forget the order in which the items were inserted.

So you'll have to keep track of it yourself, maybe keep a 'fookeys' list
besides the dict that keeps the keys, in the desired order.

-- 
Remco Gerlich



More information about the Python-list mailing list