sorting a dictionary?

Scott David Daniels Scott.Daniels at Acm.Org
Tue Mar 22 03:44:01 CET 2005


Anthony Liu wrote:
> mydict = {'the':358, 'they':29, 'went':7, 'said':65}
> Is there an easy to sort this dictionary and get a
> list like the following (in decreasing order)?
Yes.

     def sortkey((word, frequency)):
         return -frequency, word

     for word_freq in sorted(mydict.items(), key=sortkey):
         print '%-6s %s' % word_freq


--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list