Sort dictionary

Luis M. González luismgz at gmail.com
Mon Jan 2 20:22:01 EST 2006


You can't get a dictionary ordered by values, but you can get a list of
key-value pairs ordered by value:

def sortByValue(myDict):
        x = sorted( [(v,k) for k,v in myDict.items()] )
        return [(k,v) for v,k in x]

For getting only the first two pairs:

sortByValue(x)[:2]

Hope this helps...
Luis




More information about the Python-list mailing list