• Register

It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.

Suppose we have a python dictionary "our_dictionary" with the following key/value pairs:

our_dictionary = {"a":4, "c":2, "b":3, "d":1} 

To get a sorted list of key/value pairs in this dictionary based on its values,

sorted(our_dictionary.items(), key=lambda x:x[1]) 

To get a sorted list of key/value pairs in this dictionary based on its keys,

sorted(our_dictionary.items(), key=lambda x:x[0]) 

A key func is simply a normal Python function to be called on each element prior to making comparisons. The key func gets a dictionary item as its input and returns the desired “key” for the sort order comparisons.

In Python3 since unpacking is not allowed [1] we can use

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=lambda kv: kv[1])

I am writing this detailed explanation to illustrate what people often mean by "I can easily sort a dictionary by key, but how do I sort by value" - and I think the original post was trying to address such an issue. And the solution is to do sort of list of the keys, based on the values, as shown above.

1,760 points
6 1