Why are there no ordered dictionaries?

Fuzzyman fuzzyman at gmail.com
Wed Nov 23 03:27:27 EST 2005


Christoph Zwerschke wrote:
> >>I still believe that the concept of an "ordered dictionary" ("behave
> >>like dict, only keep the order of the keys") is intuitive and doesn't
> >>give you so much scope for ambiguity. But probably I need to work on an
> >>implementation to become more clear about possible hidden subtleties.
>
> Bengt Richter schrieb:
>
> > Does that mean that the Larosa/Foord odict.py implementation in PyPI
> > does not do what you want?
>
> Basically, it is what I had in mind. But I'm now seeing some things that
> could be improved/supplemented, e.g.
> - performance improvements

Implementation changes to follow, based on suggestions in this thread.
For *optimal* performance it needs to be implemented in C of course.
:-)

As F points out, a list of tuples may give you a data structure that
can be accessed quicker (although some operations will be slower). An
ordered dictionary will be a lot easier to use and make your code more
readable though.

> - the internal keys list should be hidden

I disagree. It is exposed so that you can manually change the order
(e.g. to create a "sorted" dict, rather than one ordered by key
insertion).

What do you *gain* by hiding it ?

> - list methods should be mixed in instead
>

Hmm... I did consider this. Which list methods would you consider
appropriate ?

The difficulty is that integers are valid keys for a dictionary.
Perhaps a subclass that uses integers as indexes instead...

You can always perform list operations on the ``sequence`` attribute of
course.

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

> -- Christoph




More information about the Python-list mailing list