sorting a dictionary?

Scott David Daniels Scott.Daniels at Acm.Org
Tue Mar 22 05:32:17 CET 2005


Anthony Liu wrote:
> --- Scott David Daniels <Scott.Daniels at Acm.Org> wrote:
>>     def sortkey((word, frequency)):
>>         return -frequency, word
>>     for word_freq in sorted(mydict.items(), key=sortkey):
>>         print '%-6s %s' % word_freq
> 
> Thank you scott, but 'sorted' itself is not a python library function.

For older Pythons:

     base = [(-frequency, word) for word, frequency in mydict.items()]
     base.sort()
     for negated_frequency, word in base:
          print '%-6s %s' % (word, -negated_frequency)

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



More information about the Python-list mailing list