Sort dictionary

Luis M. González luismgz at
Mon Jan 2 16:49:34 EST 2006

This function returns a tuple of value-key pairs, sorted by value:

>>> x = {'a':3, 'b':2, 'c':4}
>>> def sortByValue(myDict):
        return sorted( [(v,k) for k,v in myDict.items()] )

If you want to get the first two value-key pairs:
>>> sortByValue(x)[:2]
[(2, 'b'), (3, 'a')]

Hope this helps...

More information about the Python-list mailing list