sort dict by values in python

To sort a dictionary by its values in Python, you can use the sorted() function and provide a lambda function that returns the dictionary values as the sorting key. Here's an example code snippet:

main.py
my_dict = {'apple': 50, 'banana': 30, 'cherry': 70, 'date': 10}

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

print(sorted_dict)
# Output: {'date': 10, 'banana': 30, 'apple': 50, 'cherry': 70}
269 chars
8 lines

In the example above, we first create a dictionary my_dict with some key-value pairs of fruits and their prices. Then, we use the sorted() function to sort the dictionary by its values, with the key parameter set to a lambda function that returns the values of each item in the dictionary. The result of sorted() is a list of tuples, which we then pass to the dict() constructor to create a sorted dictionary sorted_dict. Finally, we print the sorted dictionary to verify that it is indeed sorted by its values in ascending order.

gistlibby LogSnag