Why are there no ordered dictionaries?

Fuzzyman fuzzyman at gmail.com
Wed Nov 23 03:40:54 EST 2005


Christoph Zwerschke wrote:
> One implementation detail that I think needs further consideration is in
> which way to expose the keys and to mix in list methods for ordered
> dictionaries.
>
> In http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747
> the keys are exposed via the keys() method which is bad. It should be a
> copy only, like for ordinary dicts (one comment also mentions that).
>
> In Foord/Larosa's odict, the keys are exposed as a public member which
> also seems to be a bad idea ("If you alter the sequence list so that it
> no longer reflects the contents of the dictionary, you have broken your
> OrderedDict").
>

So don't do it. ;-)

> I think it would be probably the best to hide the keys list from the
> public, but to provide list methods for reordering them (sorting,
> slicing etc.).
>
> For instance:
>
> d1 = OrderedDict( (1, 11), (2, 12), 3, 13) )
>
> d1[1:] ==> OrderedDict( (2, 12), 3, 13) )
>

So what do you want returned when you ask for d1[1] ? The member keyed
by 1, or the item in position 1 ?

You can access the members using list operations on the sequence
attribute.

E.g. d1[d1.sequence[index]]

This could probably be made more convenient.

> d1[0] + d1[2] ==> OrderedDict( (1, 11), (3, 13) )
>
> d1.reverse() ==> OrderedDict( (3, 13), (2, 12), 1, 11) )
>

Interesting idea.

> d1.insert(1, (4, 14))
>      ==> OrderedDict( (1, 11), (4, 14), (2, 12), 3, 13) )
>

Also an interesting idea.

> etc.
>
> But no other way to directly manipulate the keys should be provided.
>

Why - don't trust yourself with it ?

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

> -- Christoph




More information about the Python-list mailing list