Why are there no ordered dictionaries?

Fuzzyman fuzzyman at gmail.com
Thu Nov 24 09:36:00 CET 2005

Christoph Zwerschke wrote:
> Fuzzyman wrote:
> > So what do you want returned when you ask for d1[1] ? The member keyed
> > by 1, or the item in position 1 ?
> In case of conflict, the ordered dictionary should behave like a
> dictionary, not like a list. So d1[1] should be the member keyed by 1,
> not the item in position 1. Only in case there is no member keyed by 1,
> the item in position 1 could be returned, but I think that would be too
> adventurous a hattrick and can lead to big confusion. Better to raise a
> KeyError in that case.

I agree - hard to trace bugs lie this way....

> Instead of writing d.sequence = new_sequence, I would write
> d.setkeys(new_sequence). But I'm not sure what to do if new_sequence is
> not a permutation of the old one. Raise a KeyError? Or even swallow
> this? For instance

This is an interesting question - I don't know which is the best
behaviour here.

It's probably better to raise a KeyError - that way the error will
occur when it happens.

The simplest way of doing this is to check that the new key list
(sorted) is the same as the original one (sorted). This is potentially
quite an expensive operation.

It might be faster to compare sets with Python 2.4 - but we intend to
retain compatibility with Python 2.2.

> d = OrderedDict((1,11), (2,12))
> d.setkeys((2, 1)) ==> d = OrderedDict((2, 11), (1, 12))
> d.setkeys((3, 4)) ==> d = OrderedDict((3, 11), (4, 12)) (or KeyError?)
> d.setvalues((12, 11)) ==> d = OrderedDict((1, 12), (2, 11))
> d.setvalues((13, 14)) ==> d = OrderedDict((1, 13), (2, 14)) (always ok)
> (Or maybe better set_keys in analogy to has_key?)
> I hesitate making keys and values managed properties, because this would
> conflict with them being methods in ordinary dicts. Ordered dicts should
> resemble ordinary dicts as closely as possible. And giving it a
> different name like "sequence" I find confusing and unintuitive.

You really want to be able to set values as a sequence ? I suppose it's
even easier to implement than changing keys, but I'd never considered

> A resort could be the following: If keys() is given a sequence as
> argument, then use this as the new sequence of keys, and similar with
> values(). This way, no new methods need to be introduced.

That's not a bad idea. I'll chat with Nicola Larosa and see what he

It does break backawards compatibility of course...

All the best,


> -- Christoph

More information about the Python-list mailing list