[Python-Dev] PEP 265 - Sorting Dictionaries by Value

Guido van Rossum guido@python.org
Tue, 21 Aug 2001 20:43:33 -0400


> Seems to me that the problem is the sort method of lists is lacking
> not that dictionaries need some special smarts.

Hear, hear.

> I'd look to improve sort for some common cases where sort and lambda
> are deemed to hard. (Is using lambda a definition of hard?)
> 
> If lambda is used you would solve the problem with:
> 
> >>> items = d.items()
> >>> items.sort( lambda a, b: cmp( b[1], a[1] ) )
> 
> What if you interpret the parameter of sort:
> 
> * <missing> - do as today
> * callable -  do as today
> * int - sort by index into sequence
> * string - sort by this field of object

Or better still, list.sort() wouldn't need to be changed at all if
there was a standard library module to create compison routines, e.g.

from __future__ import nested_scopes

def cmp_by_index(i):
    return lambda a, b: cmp((a[i], a), (b[i], b))

# etc.

--Guido van Rossum (home page: http://www.python.org/~guido/)