Sorting a dictionary by value
Max M
maxm at mxm.dk
Fri Jul 5 01:51:46 EDT 2002
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()
# if you want most frequent first
sortedList.reverse()
# plain printout
for frequency, word in sortedList:
print 'word: %s, freq: %s' % (word, frequency)
# or for a faster printout of large amounts of text
print '\n'.join(['word: %s, freq: %s' % (item[1], item[0]) for item in
sortedList])
regards Max M
Hmmm seems to me that I answered this only yeasterday. Oh wait ... I did ;-)
More information about the Python-list
mailing list