Newbie Question: "How can I sort the dictionary by values() instead of keys()?"

Alexander S Coventry alex_c at mit.edu
Wed May 17 03:06:57 CEST 2000


> You can pass a sorting function as an argument to sort() which
> compares the second element of the (key, value) tuples:

That could be a little slow, though, because you have to make a
function call for each comparison in the sort.  It might be faster to
move the tails of the tuples to the heads:

l = []
for k, v in dict.items ():
    l.append ((v, k))
l.sort ()
m = []
for v, k in l:
    m.append ((k, v))

Alex.



More information about the Python-list mailing list