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
List Comprehension
Quickly generate lists using list comprehensions.
Dictionary Merging
Multiple ways to merge dictionaries.
File Read/Write
Various ways to read and write files.
CSV Processing
Read and write CSV files using the csv module.
JSON Processing
JSON serialization and deserialization.
Regex Matching
Perform regex matching using the re module.