An ordered dictionary for the Python library?

Antoon Pardon apardon at forel.vub.ac.be
Fri Sep 14 05:49:18 EDT 2007


On 2007-09-14, Mark Summerfield <m.n.summerfield at googlemail.com> wrote:
> On 14 Sep, 02:35, Jürgen Urner <jUr... at arcor.de> wrote:
>> Puh, what a discussion... most common use case I can think of is
>>
>> >> d = {'a': 1, 'b': 2, 'c': 3}
>> >> for key in d:
>> >>     # do something that relies on order of keys as specified in the constructor
>>
>> It's a bit tireing having to type
>>
>> >> for key in sorted(d.keys()):
>> >>     do_somethig_with(d[key])
>>
>> instead of a trustfully
>>
>> >> for value in d.values():
>> >>     do_somethig_with(value)
>>
>> As far as I can see much cleaner. No black magic needed ++ sort the
>> dict
>> to another order and rely on the sort order being stable would be a
>> really
>> a nice thing to have.
>>
>> My 2 cents,  Jürgen
>
> What I envisage is:
>
> d = ordereddict(a=1, x=20, b=35, m=4)
> # some time later
> d["e"] = 15
> # later still
> d["b"] = 70
> d.keys() # returns ['a', 'b', 'e', 'm', 'x']
> d.values() # returns [1, 70, 15, 4, 20]
>

which seems to be exactly what my avltree module mentioned earlier
provides.

>>> from avltree import Tree
>>> d=Tree(a=1, x=20, b=35, m=4)
>>> d["e"] = 15
>>> d["b"] = 70
>>> d.keys()
['a', 'b', 'e', 'm', 'x']
>>> d.values()
[1, 70, 15, 4, 20]

-- 
Antoon Pardon



More information about the Python-list mailing list