Skip to content
Python

Sort Dictionary by Value

Sort a Python dictionary by its values in descending order.

By EZ4Code Team
dictsortingintermediate

Code

scores = {"Alice": 85, "Bob": 92, "Carol": 78}
sorted_scores = dict(
    sorted(scores.items(), key=lambda x: x[1], reverse=True)
)
print(sorted_scores)  # {'Bob': 92, 'Alice': 85, 'Carol': 78}

Explanation

Uses sorted() with a key function to order dictionary items by value, then reconstructs a dict from the sorted items. The lambda extracts the value from each (key, value) pair for comparison. Set reverse=True for descending order; this approach works on any comparable values.

More Python Snippets