In what order does Python read dictionary keys?

Timothy R Evans tre17 at cosc.canterbury.ac.nz
Wed Jun 9 02:30:07 CEST 1999


tcpeter at my-deja.com writes:

> 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.
> 
> 
> #! /usr/bin/python
> 
> # The first thing to do is create a dictionary containing the
> # questions to be asked where the color name is the dictionary key.
> 
> entries = {'red':'Type the red value, please: ',
> 	'blue':'Type the blue value, please: ',
> 	'green':'Type the green value, please: '}
> 
> for key in entries.keys():		# Now get a loop going
> 					# through the dictionaries
> 
> 	foo = input(entries[key])	# Create a variable to hold
> 					# the return from the prompt
> 					# for each key
> 
> 	if (foo) < 16:			# Since hex numbers don't
> 					# have leading zeroes below
> 					# F, I added them.
> 
> 		print 'The hex equivalent for',foo,'is 0%X' % foo
> 	else:
> 		print 'The hex equivalent for',foo,'is %X' % foo
> 
> 
> Tim Peter
> (Not him, a different guy)
> 
> 
> Sent via Deja.com http://www.deja.com/
> Share what you know. Learn what you don't.

The order that keys are retrieved is random, from the tutorial section
5.4 on Dictionaries:

"""
The keys() method of a dictionary object returns a list of all the
keys used in the dictionary, in random order (if you want it sorted,
just apply the sort() method to the list of keys). To check whether a
single key is in the dictionary, use the has_key()method of the
dictionary.
"""

To get the keys sorted alter your loop to be:

for key in entries.keys().sort():

>From the look of this example, you probably would be better off using
a nested tuple like this:

"""
entries = (('red', 'Type the red value, please: '),
           ('green', 'Type the green value, please: '),
           ('blue', 'Type the blue value, please: '))

for key,value in entries:
...
"""

or even:

"""
entries = ('red', 'green', 'blue')

for key in entries:
    value = 'Type the ' + key + ' value, please: '
"""

This way you can control the order exactly and it might be faster as
you avoid the cost of a dictionary lookup.

--
Tim Evans





More information about the Python-list mailing list