[Tutor] Sorting a dictionary

Alan Gauld alan.gauld at freenet.co.uk
Fri Nov 4 14:40:47 CET 2005

Hi JOhan,

> 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 
be changed.

Alan G
Author of the learn to program web tutor

More information about the Tutor mailing list