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

Cliff Crawford cjc26 at
Tue May 16 18:56:00 EDT 2000

* Jae-Min Shin <shinj at> menulis:
| Hi, I am learning python.
| In  python book (Quick Python Book), I found that sorting a dictionary
| according to keys() can be done by converting it into a list, as shown
| below.. But, I don't know how to sort it by values:

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

def compare_second_elem(x, y):
    return cmp(x[1], y[1])

cmp() is a built-in function which returns -1 if x<y, 0 if x=y, or 1 if

You can also do the same thing as a one-liner, using lambda:

dic_ordered.sort(lambda x, y: cmp(x[1], y[1]))

cliff crawford    -><-
"One man's nirvana is another man's map."              icq 68165166

More information about the Python-list mailing list