Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a Python dictionary by value? [duplicate]

Tags:

python

sorting

People also ask

Can you sort a dictionary Python by value?

To sort a dictionary by value in Python you can use the sorted() function. Python's sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse. Dictionaries are unordered data structures.

How do you sort multiple values in a dictionary Python?

Sort Dictionary Using the operator Module and itemgetter() This function returns the key-value pairs of a dictionary as a list of tuples. We can sort the list of tuples by using the itemgetter() function to pull the second value of the tuple i.e. the value of the keys in the dictionary.

How do you sort a dictionary by value and then key in Python?

How to sort dictionary in Python. In Python sorted() is the built-in function that can be helpful to sort all the iterables in Python dictionary. To sort the values and keys we can use the sorted() function. This sorted function will return a new list.

How do you sort dictionaries by dictionary value?

To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.


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

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?