Sorting distionary by value
Duncan Booth
duncan at NOSPAMrcp.co.uk
Fri Mar 22 03:53:22 EST 2002
Artur Skura <arturs at iidea.pl> wrote in
news:slrna9lqj1.9n1.arturs at aph.waw.pdi.net:
> Is there an idiom in Python as to sorting dictionary by value,
> not keys? I came up with some solutions which are so inefficient
> that I'm sure there must be a simple way.
How do you know they are inefficient? Have you profiled your application
and found this to be a bottleneck?
Anyway, the idiomatic way to sort a dictionary by value, when the key
doesn't have to be saved:
values = myDictionary.values()
values.sort()
Or, if you want both keys and values:
items = [ (myDictionary[k], k) for k in myDictionary ]
items.sort()
items = [ (k, v) for (v, k) in items ]
--
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