[Tutor] Sorting a dictionary
alan.gauld at freenet.co.uk
Fri Nov 4 14:40:47 CET 2005
> You see, I didn't put all the keys and values in the dicionary manually.
> It was generated while parsing a file with some Python code, that's why
> the dict is not in order.
It wouldn't have mattered if you had done it manually. The order of
a dictionary is calculated by Python dynamically. In fact the order can even
change if you add new items later. Python always organises the dictionary to
maximise its search speed regardless of the order the data was inserted.
If you need to order the dictionary you need to use the techniques
described by the others.
> How will I then put my dict together again after sorting the items,
Don't take them out of the dictionary, just make a temporary copy for
or extract them as you go for printing. But the underlying dictionary should
Author of the learn to program web tutor
More information about the Tutor