W3docs

How do I sort a dictionary by value?

You can use the sorted() function and pass it the dictionary, along with the key parameter set to a lambda function that returns the value from the dictionary.

You can use the sorted() function and pass it the dictionary, along with the key parameter set to a lambda function that returns the value from the dictionary. For example:

Sort a dictionary's items using the sorted function in Python and returning an array

d = {'apple': 1, 'banana': 3, 'orange': 2}

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

print(sorted_d)  # Output: [('apple', 1), ('orange', 2), ('banana', 3)]

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

You can also use the sorted() function in combination with the items() method of the dictionary to sort the dictionary by value in ascending order:

Sort a dictionary's items in ascending order using the sorted function in Python and returning a new dictionary

d = {'apple': 1, 'banana': 3, 'orange': 2}

sorted_d = dict(sorted(d.items(), key=lambda x: x[1]))

print(sorted_d)  # Output: {'apple': 1, 'orange': 2, 'banana': 3}

If you want to sort the dictionary in descending order, you can use the reverse parameter of the sorted() function:

Sort a dictionary's items in descending order using the sorted function in Python and returning a new dictionary

d = {'apple': 1, 'banana': 3, 'orange': 2}

sorted_d = dict(sorted(d.items(), key=lambda x: x[1], reverse=True))

print(sorted_d)  # Output: {'banana': 3, 'orange': 2, 'apple': 1}