sorting a dictionary?

George Sakkis gsakkis at rutgers.edu
Tue Mar 22 05:24:32 CET 2005


"Anthony Liu" <antonyliu2002 at yahoo.com> wrote in message
news:mailman.698.1111460651.1799.python-list at python.org...
>
> --- Scott David Daniels <Scott.Daniels at Acm.Org> wrote:
> > 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
> >
>
> Thank you scott, but 'sorted' itself is not a python
> library function.  So I assume by
> "sorted(mydict.items()", you meant the object of
> mydict.items() which has been sorted, right?

sorted() is a new builtin in python 2.4: http://www.python.org/2.4/highlights.html

George






More information about the Python-list mailing list