lambda to Sort Dictionary.items() by Value

Duncan Booth duncan at NOSPAMrcp.co.uk
Mon Feb 18 04:33:56 EST 2002


jimd at vega.starshine.org (Jim Dennis) wrote in
news:a4p47i$13ed$1 at news.idiom.com: 

> 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)
> 
Apart from the extremely nasty way i is reused, I would have said the 
biggest improvement here would be to get rid of the lambda calls 
altogether:

    i = [(val, key) for (key, val) in h.items()]
    i.sort() # by val
    i.reverse() # Get largest first.
    result = string.join([key for (val, key) in i], "")
    return h, result

Avoiding a comparison function for sort is generally a good idea if you can 
arrange it. You could also use Python 2.2's iteritems method, but I suspect 
it won't make much difference here. Another option for the first line (in 
Python 2.2) is:
    i = [(h[key], key) for key in h]


-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list