Sorting distionary by value

Peter Hansen peter at engcorp.com
Wed Mar 27 23:02:20 EST 2002


Jim Dennis wrote:
> 
>  The core loop is something like:
> 
>         freq = {}
>         for line in file:
>                 for word in line.split():
>                         if word in freq:        freq[word] += 1
>                         else:                           freq[word] = 1
> 
>  (assuming Python2.2 for file interation and dictionary membership
>  support using "in."  I *really* like those 2.2 features!  They make
>  my psuedo-code so executable!)

Something like   freq[word] = freq.get(word, 0) + 1

would probably be faster, and it's a little simpler I think,
although I could see an argument that it's less readable.
Also doesn't depend on 2.2.

-Peter



More information about the Python-list mailing list