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

Expected output

{'banana': 1, 'cherry': 2, 'apple': 3}

Related snippets

Related DuskTools