Dictionary sorting problem

Bengt Richter bokr at oz.net
Sat Sep 17 12:36:03 EDT 2005


On 17 Sep 2005 11:01:41 GMT, Duncan Booth <duncan.booth at invalid.invalid> wrote:

>Bengt Richter wrote:
>
>> or tell sorted what to do ;-)
>> 
>> >>> original= {
>>  ... 'hello':135,
>>  ... 'goodbye':30,
>>  ... 'lucy':4,
>>  ... 'sky':55,
>>  ... 'diamonds':239843,
>>  ... 'yesterday':4 }
>> >>> list(sorted(original.iteritems(), None, lambda t:t[1], True))
>>  [('diamonds', 239843), ('hello', 135), ('sky', 55), ('goodbye', 30),
>>  ('yesterday', 4), ('lucy',4)] 
>
>or a slight variation on this theme which just gives you the keys in value 
>order rather than the tuples:
>
>>>> for k in sorted(original, key=original.get, reverse=True):
>	print k, original[k]
>
Nice. I like the keyword usage too. Much clearer than my hastypaste ;-)

>	
>diamonds 239843
>hello 135
>sky 55
>goodbye 30
>yesterday 4
>lucy 4

Regards,
Bengt Richter



More information about the Python-list mailing list