Why are there no ordered dictionaries?

Christoph Zwerschke cito at online.de
Wed Nov 23 23:28:06 CET 2005


Fuzzyman 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 ?

See my other posting. Of course hiding the list can only be done, if

>>- list methods be mixed in instead

In this case, you can change the order directly by using the list 
methods on the dictionary. Sorting would be an example. Instead of

d.sequence = sorted(d.sequence)

you could simply write d.sort() which does the same.

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

Everything method that does not clash with the use as dictionary. For 
instance, both lists and dicts have __getitem__ and __setitem__, so im 
this case, the dictionary method must take precedence. But a dictionary 
has not __getslice__ and __setslice__, so here the list methods can be 
used (__getslice__ is actually deprecated, but you get the idea). In 
some cases, like __delitem__, both have it, but there is no clash.

Other interesting methods are sort() and reverse().

Here, we have another problem however: There is not only the list of 
keys, but also the list of values, and sometimes, as in the case of 
sort() and reverse(), it would be also nice to have it operate on the 
list of values. How should this be done? PHP solves it by using two 
different methods ksort and asort for keys and values. In this notation:

d = OrderedDict( (1,13), (3,12), (2,11) )

d.ksort() ==> d = ( (1,13), (2,11), (3,12) )
d.asort() ==> d = ( (2,11), (3,12), (1,13) )

Similar for reverse().

If the keys() and values() methods would be extended to be setters, then 
d.ksort() = d.keys(sorted(d.keys())) and
d.asort() = d.values(sorted(d.values()))

Anyway, I don't like "ksort" and "asort". If it must be, I'd rather use

d.ksort() = d.sortkeys()
d.asort() = d.sortvalues()

d.sort() could default to one of them (not sure which one).

-- Christoph



More information about the Python-list mailing list