Why are there no ordered dictionaries?

Bengt Richter bokr at oz.net
Sun Nov 27 05:00:43 CET 2005


On Fri, 25 Nov 2005 19:42:49 +0000, Tom Anderson <twic at urchin.earth.li> wrote:

>On Wed, 23 Nov 2005, Carsten Haese wrote:
>
>> On Wed, 2005-11-23 at 15:17, Christoph Zwerschke wrote:
>>> Bengt Richter wrote:
>>>
>>> > E.g., it might be nice to have a mode that assumes d[key] is
>>> d.items()[k][1] when
>>> > key is an integer, and otherwise uses dict lookup, for cases where
>>> the use
>>> > case is just string dict keys.
>>>
>>> I also thought about that and I think PHP has that feature, but it's 
>>> probably better to withstand the temptation to do that. It could lead 
>>> to an awful confusion if the keys are integers.
>>
>> Thus quoth the Zen of Python:
>> "Explicit is better than implicit."
>> "In the face of ambiguity, refuse the temptation to guess."
>>
>> With those in mind, since an odict behaves mostly like a dictionary, [] 
>> should always refer to keys. An odict implementation that wants to allow 
>> access by numeric index should provide explicitly named methods for that 
>> purpose.
>
>+1
>
>Overloading [] to sometimes refer to keys and sometimes to indices is a 
>really, really, REALLY bad idea. Let's have it refer to keys, and do 
>indices either via a sequence attribute or the return value of items().
>
>More generally, if we're going to say odict is a subtype of dict, then we 
>have absolutely no choice but to make the methods that it inherits behave 
>the same way as in dict - that's what subtyping means. That means not 
>doing funky things with [], returning a copy from items() rather than a 
>live view, etc.
>
OTOH,
 >>> {}[:]
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 TypeError: unhashable type
I.e., slices are not valid keys for ordinary dicts, and slices tie in
very well with the ordered aspect of ordered dicts, so that's an
argument for permitting it via the indexing syntax, not just items[:]
or items()[:] which have related but not identical semantics.

>So, how do we provide mutatory access to the order of items? Of the 
>solutions discussed so far, i think having a separate attribute for it - 
>like items, a live view, not a copy (and probably being a variable rather 
>than a method) - is the cleanest, but i am starting to think that 
>overloading items to be a mutable sequence as well as a method is quite 
>neat. I like it in that the it combines two things - a live view of the 
>order and a copy of the order - that are really two aspects of one thing, 
>which seems elegant. However, it does strike me as rather unpythonic; it's 
>trying to cram a lot of functionality in an unexpected combination into 
>one place. Sparse is better than dense and all that. I guess the thing to 
>do is to try both out and see which users prefer.
>
I wonder who is going to use it for what.

Regards,
Bengt Richter



More information about the Python-list mailing list