Why are there no ordered dictionaries?
Bengt Richter
bokr at oz.net
Tue Nov 22 20:53:46 EST 2005
On Tue, 22 Nov 2005 20:37:40 +0100, Christoph Zwerschke <cito at online.de> 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").
>
>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.
>
>>> from odictb import OrderedDict
>>> d1 = OrderedDict([(1, 11), (2, 12), (3, 13)])
>>> d1
{1: 11, 2: 12, 3: 13}
>>> d1[1:]
{2: 12, 3: 13}
>>> d1[0:1] + d1[2:3]
{1: 11, 3: 13}
>>> d1.reverse()
>>> d1
{3: 13, 2: 12, 1: 11}
>>> d1.insert(1, (4,14))
>>> d1
{3: 13, 4: 14, 2: 12, 1: 11}
>>> d1.items()
[(3, 13), (4, 14), (2, 12), (1, 11)]
>>> d1.keys()
[3, 4, 2, 1]
>>> d1.values()
[13, 14, 12, 11]
>>> d1[1:2]
{4: 14}
>>> d1[-1:]
{1: 11}
Que mas?
Regards,
Bengt Richter
More information about the Python-list
mailing list