Sort dictionary

Luis M. González luismgz at gmail.com
Mon Jan 2 22:38:52 CET 2006


This function return 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...
Luis




More information about the Python-list mailing list