Sorting distionary by value

Terry Reedy tejarex at yahoo.com
Sat Mar 23 10:23:12 EST 2002


"John Machin" <sjmachin at lexicon.net> wrote in message
news:c76ff6fc.0203230339.48961684 at posting.google.com...
> Paul Rubin <phr-n2002a at nightsong.com> wrote in message
news:<7xd6xwntgx.fsf at ruckus.brouhaha.com>...
> > counts = {}
> > a = string.split(open(sys.argv[1],'r').read())
> > for w in a:
> >   if counts.has_key(w):
> >      counts[w] += 1
> >   else:
> >      counts[w] = 1
> >
> > words = counts.keys()
> > words.sort()
> > words.reverse()
> >
> > for w in words:
> >    print words[w], w
>
> Sorry, but this doesn't work. If you were to actually *run* your
code,
> you would get this result [after adding
>
> import string, sys
>
> at the start of the script]:
>
>     print words[w], w
> TypeError: sequence index must be integer
...
> Try replacing the last part of the script with:
>
> words = [(-count, word) for word, count in counts.items()]
> words.sort()
> for count, word in words:
>    print word, -count

or, I believe, change the last line to
     print counts[w], w






More information about the Python-list mailing list