Sorting a dictionary by value

Alex Martelli aleax at aleax.it
Fri Jul 5 10:49:36 EDT 2002


Max M wrote:

> Roy Culley wrote:
>> I'm sorry if this is a novice question but I have searched google
>> and the python FAQ and haven't found an answer.
>> 
>> I have a large dictionary where I want to sort and print based
>> on the largest values in a dictionary and not the keys.
>> 
>> Now in perl you can do:
>> 
>>     @Keys = sort { $Hash{$b} <=> $Hash{$a} } keys %Hash;
>> 
>> Is there any such magic for python?
> 
> # the basic sort
> sortedList = [(key, theDict[key]) for key in theDict.keys()]
> sortedList.sort()

This sort by key, not by value.  And if that's what you want,
sortedList = theDict.items() is a faster and more compact
way to perform the first of these two statements.

To sort by value, largest-first, as it appears Roy Culley is asking,
you need something like:

histogram = [ (value, key) for key, value in theDict.iteritems() ]
histogram.sort()
histogram.reverse()


Alex




More information about the Python-list mailing list