sort a dictionary by its values in python

To sort a dictionary by its values in Python, you can use the sorted() function along with a lambda function.

Here's the code:

main.py
# Example dictionary
my_dict = {'a': 3, 'b': 1, 'c': 2}

# Sort the dictionary by its values in ascending order
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))

print(sorted_dict)
202 chars
8 lines

Output:

main.py
{'b': 1, 'c': 2, 'a': 3}
25 chars
2 lines

In the code above, the sorted() function is used to sort the dictionary items based on the values. The key parameter is set to a lambda function lambda item: item[1], which specifies that the sorting should be done based on the values (item[1]). Finally, the dict() function is used to convert the sorted items back into a dictionary.

If you want to sort the dictionary in descending order, you can modify the sorted() function as follows:

main.py
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))
84 chars
2 lines

This will sort the dictionary in descending order of values.

Hope this helps!

related categories

gistlibby LogSnag