[Tutor] Re: Question about order in a dictionary

Andrei project5 at redrival.net
Mon Jun 28 04:44:34 EDT 2004


Dick Moores <rdmoores <at> gmail.com> writes:

> In IDLE, if I enter
> D = {"a": "first letter", "b": "second letter", "c": "third letter",
> "z": "last letter"}
> and then 
> print D
> I get 
> {'a': 'first letter', 'c': 'third letter', 'b': 'second letter', 'z':
> 'last letter'}
> 
> Why does the order change? I'm just beginning to understand

For the order to change, there should be an order in the first place. However,
dictionary by definition have *no order*, so how can it possibly change if it
doesn't exist? Don't be fooled by the fact that things are printed in a certain
order; that order is for all intents and purposes meaningless and is there for
the simple reason that we are only able to read things when they're presented
sequentially (and therefore ordered).

> dictionaries, and I suppose the order doesn't matter, but why would it
> change?

You might have asked the wong question and actually want to know why
dictionaries are not ordered. That has to do with their implementation. You can
read about that in the FAQ:
http://www.python.org/doc/faq/general.html#how-are-dictionaries-implemented

By the way, it's possible (and not that hard) to roll your own implementation of
dictionary which *is* ordered. In fact, there are several available on the web
if you need one and don't much care for coding your own ;).

Yours,

Andrei




More information about the Tutor mailing list