[Tutor] Question about order in a dictionary
Alan Gauld
alan.gauld at blueyonder.co.uk
Mon Jun 28 13:28:38 EDT 2004
> D = {"a": "first letter", "b": "second letter", "c": "third letter",
> "z": "last letter"}
> print D
> {'a': 'first letter', 'c': 'third letter', 'b': 'second letter',
'z':
> 'last letter'}
>
> Why does the order change?
Because of the way Python stores the data internally. To make the
search fast it doesn't use the sequence that you provide but uses
a tree-like structure. When you print D it traverses the tree top
to bottom, but the position in the tree is optimised for rapid
retrieval of the keys.
> I suppose the order doesn't matter, but why would it change?
You are right the order doesn't matter to the user, and you can
always extract the list of keys and sort them if you need sorted
order.
You might find my "Raw Materials" topic in my tutor usful it has
a section on Dictionaries which discusses these issues a little
further.
Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list