Access dictionary in order?

Michael P. Reilly arcege at shore.net
Sun Jul 25 18:17:10 EDT 1999


Skip Montanaro <skip at mojam.com> wrote:

:     Roy> I've got a dictionary of items which I will sometimes want random access
:     Roy> to, but sometimes I'll want to be able to step through the items in a
:     Roy> fixed order as well.  Any good way to do that?

: You demonstrated the best way.  There is no need to save the key list unless
: the dictionary is very large though.  Just grab 'em and sort 'em when you
: need:

:     keylist = dict.keys()
:     keylist.sort()
:     for key in keylist: do_stuff(dict[key])

There are times when the entries cannot be sorted and the order must
still be preserved.

A good way to handle this is a modified UserDict subclass.

  from UserDict import UserDict
  class OrderedDict(UserDict):
    def __init__(self, dict=None):
      UserDict.__init__(self, dict)
      if dict and isinstance(dict, OrderedDict)
        self.ordered = dict.ordered[:]
      elif dict:
        self.ordered = dict.values()  # must be taken unordered
      else:
        self.ordered = []
    def __getitem__(self, index):
      if isinstance(index, type(0)):
        return self.ordered[index]
      else:
        return UserDict.__getitem__(self, index)
    def __setitem__(self, index):
      UserDict.__setitem__(self, index, value)
      self.ordered.append(value)

One problem to this mechanism is that numbers are not indices instead
of keys.  But you can do this in other ways to fill the application's
needs.

Remember that you aren't creating copies of the objects, just references
to the same object, so you should be creating only twice the memory
space as the dictionary itself (relatively speaking).

  -Arcege





More information about the Python-list mailing list