Sort Dictionary by Value
Sort a dictionary by its values (ascending or descending).
Code
Python
data = {"apple": 3, "banana": 1, "cherry": 2}
# Ascending
sorted_asc = dict(sorted(data.items(), key=lambda x: x[1]))
print(sorted_asc)
# Descending
sorted_desc = dict(sorted(data.items(), key=lambda x: x[1], reverse=True))
print(sorted_desc)Line-by-line explanation
- 1.data.items() yields (key, value) pairs.
- 2.key=lambda x: x[1] sorts by the value (index 1).
- 3.reverse=True for descending order.
- 4.dict() converts the sorted list of tuples back to a dict.
Expected output
{'banana': 1, 'cherry': 2, 'apple': 3}