Sort Dictionary by Value
Sort Dictionary by Value is a reusable Python snippet. Sorts a dictionary by its values using `sorted()` with a lambda key function. The full implementation: # Sort by value (ascending) scores = {"Alice": 85, "Bob": 92, "Charlie": 78, "Diana": 95} sorted_scores = dict(sorted(scores.items(), key=lambda x: x[1])) # {"Charlie": 78, "Alice": 85, "Bob": 92, "Diana": 95} # Descending sorted_desc = dict(sorted(scores.items(), key=lambda x: x[1], reverse=True)) # {"Diana": 95, "Bob": 92, "Alice": 85, "Charlie": 78} # Sort by value then key sorted_by_both = dict(sorted(scores.items(), key=lambda x: (-x[1], x[0]))) It belongs to the Built-in Functions area of the standard library. This snippet uses only the Python standard library with no third-party dependencies, so it runs on any modern Python 3 interpreter. Browse more patterns in the snippet library, or paste the code straight into the playground to experiment with it.