[Newbie] How to output dictionary sorted on content (not keys)
Max M
maxm at mxm.dk
Thu Jul 4 09:39:44 EDT 2002
Ben Fairbank wrote:
> I have several long (thousands of entries) dictionaries of words used
> in plays; associated with each word is the number of times it is used
> in the play. I have had no problem printing the words alphabetically
> (send keys to a list, sort the list, access dictionary by the sorted
> key list), but I have not found an elegant way to sort by frequency
> of use. The best I have been able to do is a workable but inelegant
> kluge that looks more like Basic than Python. Is there a "Python Way"
> of doing that?
# 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
More information about the Python-list
mailing list