Why are there no ordered dictionaries?

Bengt Richter bokr at oz.net
Sun Nov 20 23:53:54 EST 2005


On Sun, 20 Nov 2005 22:03:34 +0100, Christoph Zwerschke <cito at online.de> wrote:
>> Ordering the keys isn't the normal case, and can be done easily when
>> needed.
>
>That depends. Maybe I do not want the keys to be sorted alphabetically, 
>but according to some criteria which cannot be derived from the keys 
>themselves.
You mean involving also the values? What's wrong with
    sorted(plaindict.items(), key=your_ordering_function) ?

 >>> def show(*a): print a
 ...
 >>> sorted(dict((c,ord(c)) for c in 'abcd').items(), key=show)
 (('a', 97),)
 (('c', 99),)
 (('b', 98),)
 (('d', 100),)
 [('a', 97), ('c', 99), ('b', 98), ('d', 100)]

What key function would you like, to generate the value that is actually used
to define the ordering?

 >>> sorted(dict((c,ord(c)) for c in 'abcd').items(), key=lambda t:t[0])
 [('a', 97), ('b', 98), ('c', 99), ('d', 100)]
 >>> sorted(dict((c,ord(c)) for c in 'abcd').items(), key=lambda t:t[1])
 [('a', 97), ('b', 98), ('c', 99), ('d', 100)]
 >>> sorted(dict((c,ord(c)) for c in 'abcd').items(), key=lambda t:-t[1])
 [('d', 100), ('c', 99), ('b', 98), ('a', 97)]
 >>> sorted(dict((c,ord(c)) for c in 'abcd').items(), key=lambda t:t[1]&1)
 [('b', 98), ('d', 100), ('a', 97), ('c', 99)]
 >>> sorted(dict((c,ord(c)) for c in 'abcd').items(), key=lambda t:(t[1]&1,t[1]))
 [('b', 98), ('d', 100), ('a', 97), ('c', 99)]
 >>> sorted(dict((c,ord(c)) for c in 'abcd').items(), key=lambda t:(t[1]&1,-t[1]))
 [('d', 100), ('b', 98), ('c', 99), ('a', 97)]
And being able to reverse the end result is handy
 >>> sorted(dict((c,ord(c)) for c in 'abcd').items(), key=lambda t:(t[1]&1,-t[1]), reverse=True)
 [('a', 97), ('c', 99), ('b', 98), ('d', 100)]

You may need to upgrade your Python though ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list