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

Barry Scott barry@scottb.demon.co.uk
Wed, 22 Aug 2001 00:21:53 +0100


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

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

If you had the improved sort you could:

>>> items = d.items()
>>> items.sort( 1 )
>>> items.reverse()

		BArry

> For example, given an occurrence count of:
> 
>  >>> d = {'a':2, 'b':23, 'c':5, 'd':17, 'e':1}
> 
> we might do:
> 
>  >>> items = d.items()
>  >>> items = [(v, k) for (k, v) in items]
>  >>> items.sort()
>  >>> items.reverse()		# so largest is first
>  >>> items = [(k, v) for (v, k) in items]
> 
> resulting in:
> 
>  >>> items
> [('b', 23), ('d', 17), ('c', 5), ('a', 2), ('e', 1)]
>