Sorting distionary by value

John Machin sjmachin at lexicon.net
Sat Mar 23 16:05:03 EST 2002


"Terry Reedy" <tejarex at yahoo.com> wrote in message news:<A51n8.216264$uv5.18611282 at bin6.nnrp.aus1.giganews.com>...
> "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

The basis for whatever it is you believe apparently doesn't include
running the code. The effect of the above change is to list the
results in reverse *word* order irrespective of the frequencies of
those words e.g.

42 zot
1 foo
666 bar

Anybody who considers this result to be useful, please post, as I
would be delighted to converse with you.

Cheers,
John



More information about the Python-list mailing list