0
0
PythonHow-ToBeginner · 3 min read

How to Sort Dictionary by Value in Python Quickly

To sort a dictionary by its values in Python, use the sorted() function with a lambda that extracts the dictionary's values. This returns a list of tuples sorted by value, which you can convert back to a dictionary if needed.
📐

Syntax

Use sorted() with dict.items() and a lambda function to sort by values.

  • sorted_dict = dict(sorted(original_dict.items(), key=lambda item: item[1]))
  • original_dict.items() gets key-value pairs.
  • key=lambda item: item[1] tells sorted() to sort by the value part.
  • dict() converts the sorted list of tuples back to a dictionary.
python
sorted_dict = dict(sorted(original_dict.items(), key=lambda item: item[1]))
💻

Example

This example shows how to sort a dictionary by its values in ascending order and print the sorted dictionary.

python
original_dict = {'apple': 5, 'banana': 2, 'cherry': 7, 'date': 3}
sorted_dict = dict(sorted(original_dict.items(), key=lambda item: item[1]))
print(sorted_dict)
Output
{'banana': 2, 'date': 3, 'apple': 5, 'cherry': 7}
⚠️

Common Pitfalls

One common mistake is trying to sort the dictionary directly without using items(), which causes errors because dictionaries are unordered collections of keys.

Another is forgetting that sorted() returns a list, so you need to convert it back to a dictionary if you want a dictionary result.

python
wrong = sorted(original_dict)  # This sorts keys, not values

# Correct way:
sorted_dict = dict(sorted(original_dict.items(), key=lambda item: item[1]))
📊

Quick Reference

Tips for sorting dictionaries by value:

  • Use sorted(dict.items(), key=lambda item: item[1]) to sort by values.
  • Wrap with dict() to get a dictionary back.
  • Use reverse=True in sorted() to sort descending.

Key Takeaways

Use sorted() with dict.items() and a lambda to sort by dictionary values.
sorted() returns a list of tuples; convert it back to dict() if needed.
To sort descending, add reverse=True to sorted().
Sorting directly on a dictionary sorts keys, not values.
Always use the key parameter to specify sorting by values.