A dictionary iteration (which the sorted
function sorted
) will give you only its keys:
>>> sorted(mydict) [u'den', u'jaime', u'jon', u'rob']
Instead, you want to sort both keys and values ββ- for this you should use mydict.items()
(or mydict.iteritems()
, which is more efficient with large dicts):
>>> sorted(mydict.items()) [(u'den', 26), (u'jaime', 31), (u'jon', 30), (u'rob', 42)]
Then your code will work as expected:
>>> from operator import itemgetter >>> sorted(mydict.items(), key = itemgetter(1)) [(u'den', 26), (u'jon', 30), (u'jaime', 31), (u'rob', 42)]
You can also sort using the dict key as a secondary sort value if multiple keys have the same value:
>>> mydict={u'a': 1, 'z': 1, 'd': 1} >>> sorted(mydict.items(), key = itemgetter(1)) [(u'a', 1), ('z', 1), ('d', 1)] >>> sorted(mydict.items(), key = itemgetter(1, 0)) [(u'a', 1), ('d', 1), ('z', 1)]