Here’s how to do it without converting to a list of dictionaries:
Sort by values (ascending):
sorted_items = sorted(my_dict.items(), key=lambda item: item[1])
Sort by values (descending):
sorted_items = sorted(my_dict.items(), key=lambda item: item[1],reverse=True)
This returns a list of (key, value) tuples sorted by value.
my_dict = {
'apple': 10,
'banana': 2,
'cherry': 7
}
# Ascending sort by value
sorted_items = sorted(my_dict.items(), key=lambda x: x[1])
print(sorted_items)
# Output: [('banana', 2), ('cherry', 7), ('apple', 10)]
# Descending sort by value
sorted_items = sorted(my_dict.items(), key=lambda x: x[1], reverse=True)
print(sorted_items)
# Output: [('apple', 10), ('cherry', 7), ('banana', 2)]
If you want the result back as a dict (e.g., for further use):
sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1]))
Note: Regular Python dicts preserve insertion order as of Python 3.7+ (officially guaranteed in 3.8+), so this will maintain the sorted order.
Work with our skilled Python developers to accelerate your project and boost its performance.
Hire Python Developers