Why are there no ordered dictionaries?

Christoph Zwerschke cito at online.de
Tue Nov 22 20:37:40 CET 2005


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").

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) )

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

d1.reverse() ==> OrderedDict( (3, 13), (2, 12), 1, 11) )

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

etc.

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

-- Christoph



More information about the Python-list mailing list