Sort Python dictionary by value

Sort Python dictionary by value

With Python list, you can sort it by calling sorted built-in function. With dictionary, the thing is kind of similar

Note
It is noticable that we can not sort a dictionary, only to get a representation of a dictionary that is sorted, in this case, it is a sorted list of tuple
original_dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}

Using sorted function and operator module

import operator
sorted_x = sorted(original_dict.items(), key=operator.itemgetter(1))
print(sorted_x)

Out:

[('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)]

Using sorted function and lambda

sorted_by_value = sorted(original_dict.items(), key=lambda kv: kv[1])
print(sorted_by_value)

And we will get the same output:

[('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)]

A nice solution with lambda:

sorted_by_value = sorted(original_dict.items(), key=lambda (k, v): v)
print(sorted_by_value)

Sort dictionary by value descending

There are 2 option you can sort dictionary by descending

  • Call reverse() function on sorted returned list

    sorted_by_value.reverse()
    print(sorted_by_value)

Output:

[('five', 5), ('four', 4), ('three', 3), ('two', 2), ('one', 1)]
  • Pass reverse=True parameter to sorted function

    sorted_by_value = sorted(
    original_dict.items(), key=lambda kv: kv[1], reverse=True)
    print(sorted_by_valu

Of course the output is same as above

Last modified October 4, 2020