sorting a dictionary?
Bengt Richter
bokr at oz.net
Wed Mar 23 17:39:18 EST 2005
On Wed, 23 Mar 2005 06:27:08 GMT, Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote:
>On Tue, 22 Mar 2005 14:13:00 +1200, "Tony Meyer" <t-meyer at ihug.co.nz>
>declaimed the following in comp.lang.python:
>
>>
>> There are no doubt faster and cleverer ways to do this (and ways that don't
>> use a lambda), but this works...
>>
>
> Well, no lambda, but probably not much clearer...
>
>>>> mydict = {'the':358, 'they':29, 'went':7, 'said':65}
>>>> tmp = [(v,k) for (k,v) in mydict.items()]
>>>> tmp.sort()
>>>> tmp.reverse()
>>>> for (v,k) in tmp:
>... print k, v
>...
>the 358
>said 65
>they 29
>went 7
>>>>
>
> Did they add sorted() and reversed() to 2.4? That would allow
>compressing the middle down to
>
> tmp = [(v,k) for (k,v) in mydict.items()].sorted().reversed()
>
They added them, but not as list methods:
>>> mydict = {'the':358, 'they':29, 'went':7, 'said':65}
>>> for v,k in reversed(sorted((v,k) for k,v in mydict.items())): print k,v
...
the 358
said 65
they 29
went 7
Regards,
Bengt Richter
More information about the Python-list
mailing list