Learning Python via a little word frequency program

Peter Otten __peter__ at web.de
Wed Jan 9 07:22:04 EST 2008


Andrew Savige wrote:

> Fredrik Lundh wrote:
> 
>>    # sort items on descending count
>>    deco = sorted(freq.items(), key=lambda x: -x[1])
> 
> Neat. Is there any way to use sorted() with multiple sort keys? ...
> Given that the spec calls for sorting by _two_ keys: first by
> frequency (descending), then by name (ascending). To clarify:
> 
> kevin     : 3
> jock      : 2
> andrew    : 1
> bill      : 1
> fred      : 1
> freddy    : 1
> 
> is correct, while:
> 
> kevin     : 3
> jock      : 2
> bill      : 1
> andrew    : 1
> fred      : 1
> freddy    : 1
> 
> is incorrect because "andrew 1" must appear before "bill 1".

You can sort twice (on the name, then on the number) or use a more complex
key:

>>> for n, v in sorted(freq.items(), key=lambda (n, v): (-v, n)):
...     print n, v
... 
kevin 3
jock 2
andrew 1
bill 1
fred 1
freddy 1

>>> items = freq.items()
>>> items.sort(key=itemgetter(0))
>>> items.sort(key=itemgetter(1), reverse=True)
>>> for n, v in items:
...     print n, v
... 
kevin 3
jock 2
andrew 1
bill 1
fred 1
freddy 1

Peter



More information about the Python-list mailing list