lambda to Sort Dictionary.items() by Value

Alex Martelli aleax at aleax.it
Mon Feb 18 03:33:23 EST 2002


Jim Dennis wrote:

>  I'm playing with text and I decided to write a simple histogram
>  function (calculating letter occurence frequencies, in this case).
> 
>  In the course of that I found two simple uses for lambda one of
>  which seems like it would be a very common idiom in Python.

Fortunately not, because decorate-sort-undecorate (DSU) is faster
and more general.

>     i = h.items()
>     i.sort(lambda (k1,v1),(k2,v2): cmp(v2,v1) ) # sort by value, not by
>     key
>     i=string.join(map(lambda (x,y):x, i),"")  # extract letters from each
>     return (h,i)

Try instead (Python 2.2, but it's similar in older Pythons, 2.0 & later):
    temp = [ (h[key], key) for key in h ]
    temp.sort()
    return h, ''.join([ key for value, key in temp ])

>  It seems like one might need to sort dictionary items by value
>  pretty often.

Depends on your application field, but DSU and list comprehensions
help when you do have such needs.


Alex




More information about the Python-list mailing list