Mailing List Archive

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.


#! /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.
In what order does Python read dictionary keys? [ In reply to ]
tcpeter@my-deja.com wrote:
>
> 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.

Hi there,

The answer is that Python doesn't have any set orders for dictionaries.
The internal hashing algorithm the python dictionary uses has no
guaranteed order. So basically you shouldn't depend on any particular
order it produces.

Regards,

Martijn
In what order does Python read dictionary keys? [ In reply to ]
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@fenx.com
-------------------


----- Original Message -----
From: <tcpeter@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.
>
...
In what order does Python read dictionary keys? [ In reply to ]
Emile van Sebille (emile@fenx.com) wrote:
: ... is there a way to combine these
: two steps into a single statement, along the lines of:
: entrieskeys=entries.keys().sort()

That won't work as written, since sort() doesn't return anything. But
you can easily do it with a function.

def sortedDictionaryKeys(d):
k = d.keys()
k.sort()
return k

print sortedDictionaryKeys({'r':1, 'g':2, 'b':3})
===> ['b', 'g', 'r']
--
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Will Ware email: wware[at]world[dot]std[dot]com
PGP fp (new key 07/15/97) 67683AE2 173FE781 A0D99636 0EAE6117
In what order does Python read dictionary keys? [ In reply to ]
In article <375D8077.EA539C6D@pop.vet.uu.nl>,
M.Faassen@vet.uu.nl wrote:
> tcpeter@my-deja.com wrote:
>> 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.
>
> Hi there,
>
> The answer is that Python doesn't have any set orders for
dictionaries.
> The internal hashing algorithm the python dictionary uses has no
> guaranteed order. So basically you shouldn't depend on any particular
> order it produces.

OK. So is there a way to ensure a specific order? In this instance
I've given it's not particularly critical, but there are times where it
might be. Any ideas?


Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.
In what order does Python read dictionary keys? [ In reply to ]
tcpeter@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
In what order does Python read dictionary keys? [ In reply to ]
Timothy R Evans <tre17@cosc.canterbury.ac.nz> wrote:

: To get the keys sorted alter your loop to be:

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

The right idea, but the wrong implimentation. Unfortunately, sort()
does not return the sorted list, it sorts in-place.

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

: 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.

If this was only for these three values, tuples would be the most
efficient.

But in general (outside of the question now) tuples can't be searched
easily, I would suggest either the dictionary or a list (with the
'index' method).

You can also make a subclass of UserDict with the proper ordering:

class Colors(UserDict):
ordered_keys = ('red', 'green', blue')
def keys(self):
l = []
for key in self.ordered_keys:
if self.has_key(key):
l.append(key)
return l
def items(self):
l = []
for key in self.keys():
l.append( (key, self[key]) )
return l
def values(self):
l = []
for key in self.keys():
l.append( self[key] )
return l

This makes it all work like you desire, at the expense of a little more
processing.

-Arcege
In what order does Python read dictionary keys? [ In reply to ]
On Tue, 8 Jun 1999 tcpeter@my-deja.com wrote:

<about the order of keys()>
>
> OK. So is there a way to ensure a specific order? In this instance
> I've given it's not particularly critical, but there are times where it
> might be. Any ideas?

Subclass UserDict.UserDict.
--
Moshe Zadka <mzadka@geocities.com>.
QOTD: My own exit is more likely to be horizontal then perpendicular.