Why are there no ordered dictionaries?

Alex Martelli aleax at mail.comcast.net
Wed Nov 23 11:24:40 EST 2005


Fuzzyman <fuzzyman at gmail.com> wrote:
   ...
> > - 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 ?

Freedom of implementation, of course.  E.g., I can perhaps get better
performance by keeping a red-black tree of (insertiontime,key) pairs, so
for example deleting a key is O(log(N)) rather than O(N) as it would
have to be if the sequence had to be kept as a Python list.

What ELSE do you ever gain by enforcing abstraction and information
hiding?  Conceptual integrity and implementation freedom...


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

What about allowing slicing, taking advantage of the fact that slices
are NOT valid dictionary keys?
Presumably sort and reverse methods are also desired.

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

But NOT having to expose .sequence as a real mutable list whose changes
affect ordering has many advantages, as above noticed.


Alex



More information about the Python-list mailing list