Why are there no ordered dictionaries?

Tom Anderson twic at urchin.earth.li
Fri Nov 25 14:42:49 EST 2005


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.

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.

tom

-- 
YOU HAVE NO CHANCE TO ARRIVE MAKE ALTERNATIVE TRAVEL ARRANGEMENTS. --
Robin May



More information about the Python-list mailing list