sort dictionary by value

bas.vangils at home.nl bas.vangils at home.nl
Wed Apr 11 14:05:37 EDT 2001


Robin Thomas <robin.thomas at starmedia.net> wrote:

 * Q: Can dictionaries be sorted?

 * A: No. Dictionaries have no concept of ordering of their items, such that 
 * the items can be "re-ordered" in the dictionary by sorting them.

ehh I knew that...


 * Q: Can I retrieve all of the items in a dictionary and sort them?

 * A: Yes.

true, that is what I meant ...


 *  >>> d  = some_big_dictionary()
 *  >>> i = d.items()
 * # sort by value
 *  >>> i.sort(lambda x,y: cmp(x[1],y[1]))
 * # sort by key
 *  >>> i.sort(lambda x,y: cmp(x[0],y[0]))

and that's the one which probably solves my problem. So, thanks a lot


-- 
Bas van Gils <bas.vangils at home.nl>
An invasion of armies can be resisted, but not an idea whose time has come.
                                                           (Victor Hugo) 



More information about the Python-list mailing list