[Tutor] Keeping Dictonary Entries Ordered

Alan Gauld alan.gauld at btinternet.com
Thu Feb 12 10:25:22 CET 2009


"Wayne Watson" <sierra_mtnview at sbcglobal.net> wrote

> config_names = {"start_time : '18:00:00', 'gray_scale' : True, 
> "long": 120.00}
>
> If I iterate over it, the entries will appear in any order, as 
> opposed to
> what I see above. However, in the config file, I'd like to keep them
> in the order above.

Thats tricky! Dictionaries are not sorted and do not retain insertion 
order.
If you can define a sort order you can use sorted:

>>> d = {1:2, 3:4, 8:9, 5:7}
>>> for n in d: print n
...
8
1
3
5
>>> for n in sorted(d): print n
...
1
3
5
8
>>>

But you need to have an order that will work with sorted().
Its not just the order you add items to the dict. To store an
arbitrary order I suspect you would need to maintain a
secondary list with the keys in the order of insertion.
The most reliable way to dop that would be to subclass
dict. Somebody may already have done that so its worth
a google...

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list