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. For example:

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)]

Watch a course Python - The Practical Guide

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:

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:

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}