In what order does Python read dictionary keys?

Michael P. Reilly arcege at
Wed Jun 9 04:30:57 CEST 1999

Timothy R Evans <tre17 at> 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()
  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

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


More information about the Python-list mailing list