How do I sort a dictionary by value?

Created by Devin JeanpierreLinked to 82.5m issues across 249 teams

tl;dr

Sorting a dictionary by value in Python can be done in a few different ways. The simplest way is to use the built-in sorted() function. This function takes a dictionary as an argument and returns a list of tuples sorted by the second element in each tuple. For example, if you have a dictionary x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}, you can sort it by value using the following code:

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

This will return a list of tuples sorted by the second element in each tuple, such as [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]. To convert this back into a dictionary, you can use the dict() function:

dict(sorted_x) == x

In older versions of Python, you can use the operator module to sort the dictionary by value. For example, if you have a dictionary x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}, you can sort it by value using the following code:

import operator x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=operator.itemgetter(1))

This will return a list of tuples sorted by the second element in each tuple, such as [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]. To convert this back into a dictionary, you can use the dict() function:

dict(sorted_x) == x
We use cookies to personalize content
run ads, and analyze traffic.