How to sort a Python dictionary by value?

In your example you are using list of dictionaries. Sorting the dict by key:

mydict = {'carl':40,
          'alan':2,
          'bob':1,
          'danny':3}

for key in sorted(mydict.iterkeys()):
    print "%s: %s" % (key, mydict[key])

alan: 2
bob: 1
carl: 40
danny: 3

If you want to sort a dict by values, please see How do I sort a dictionary by value?


Dictionaries can't be sorted as such, but you can sort their contents:

sorted(a_dict.items(), key=lambda (k, (v1, v2)): v2)
sorted(a_dict.items(), key=lambda item: item[1][1])    # Python 3

You can put the results into a collections.OrderedDict (since 2.7):

OrderedDict(sorted(a_dict.items(), key=lambda (k, (v1, v2)): v2))
OrderedDict(sorted(a_dict.items(), key=lambda item: item[1][1])    # Python 3

Tags:

Python

Sorting