In what order does Python read dictionary keys?

Emile van Sebille emile at fenx.com
Tue Jun 8 18:04:13 EDT 1999


Tim,

"Note that the printed representation for the dictionary lists the entries
in a different order than in the assignment because dictionaries are
unordered "sets" of pairs, and the implementation reserves the right to
print out the content in any order it pleases (so there!)."
    -From "Internet Programming with Python"
    -Watters, van Rossum & Ahlstrom

What you want to do is use sort:

>>> entries = {'red':'Type the red value, please: ',
'blue':'Type the blue value, please: ',
'green':'Type the green value, please: '}

>>> entrieskeys=entries.keys()
>>> entrieskeys.sort()

>>> for key in entrieskeys: # Now get a loop going

A related question for those in the know, is there a way to combine these
two steps into a single statement, along the lines of:

entrieskeys=entries.keys().sort()


Emile van Sebille
emile at fenx.com
-------------------


----- Original Message -----
From: <tcpeter at my-deja.com>
Newsgroups: comp.lang.python
Sent: Tuesday, June 08, 1999 11:37 AM
Subject: In what order does Python read dictionary keys?


> Hello, all.  I've checked the docs and queried DejaNews for this but I
> couldn't come up with an answer.  I wrote a script to convert rgb
> values to hex for when I'm doing colors in HTML pages and don't have
> Photoshop handy.  The code appears below.  My question is, how does
> Python decide in which order to read the keys?  Notice that I have the
> dictionary set up in this order: red, blue, green.  (I mistyped it while
> writing the code).  But when I ran the code, the options were presented
> in the desired order. (A trifle creepy, if you ask me.  Turing would be
> delighted.)  Anyway, how does Python decide the order. Thanks.
>
...









More information about the Python-list mailing list