How do I sort a dictionary by value in Python?

To sort a dictionary by its values in Python, you can use the sorted() function along with a key parameter. Here’s how to do it in both ascending and descending order, with explanations:

1. Sort by Value (Ascending Order)

my_dict = {'apple': 5, 'banana': 2, 'cherry': 8}

# Step 1: Convert dictionary items to a sorted list of tuples
sorted_items = sorted(my_dict.items(), key=lambda x: x[1])

# Step 2: Convert the sorted list back into a dictionary
sorted_dict = dict(sorted_items)

print(sorted_dict)
# Output: {'banana': 2, 'apple': 5, 'cherry': 8}

2. Sort by Value (Descending Order)

sorted_items_desc = sorted(my_dict.items(), key=lambda x: x[1], reverse=True)
sorted_dict_desc = dict(sorted_items_desc)

print(sorted_dict_desc)
# Output: {'cherry': 8, 'apple': 5, 'banana': 2}

3. Using operator.itemgetter (Faster for Large Data)

The operator module can improve performance for large datasets:

from operator import itemgetter

sorted_items = sorted(my_dict.items(), key=itemgetter(1))
sorted_dict = dict(sorted_items)

4. Handling Older Python Versions (<3.7)

For versions where dictionaries do not preserve order, use collections.OrderedDict:

from collections import OrderedDict

sorted_items = sorted(my_dict.items(), key=lambda x: x[1])
ordered_dict = OrderedDict(sorted_items)

Key Notes

  • Dictionary Order: Python 3.7+ preserves insertion order, so the sorted result will maintain the new order.
  • Immutable Result: Dictionaries themselves are not sorted in-place; a new sorted dictionary is created.
  • Complex Values: Works with any comparable values (e.g., numbers, strings, dates).

Example Workflow

# Original dictionary
scores = {'Alice': 90, 'Bob': 75, 'Charlie': 85}

# Sort by ascending scores
sorted_scores = dict(sorted(scores.items(), key=lambda x: x[1]))

print(sorted_scores)
# Output: {'Bob': 75, 'Charlie': 85, 'Alice': 90}

Summary

MethodUse CaseExample Code
sorted() + lambdaSimple value sortingsorted(d.items(), key=lambda x: x[1])
operator.itemgetterFaster for large datasetssorted(d.items(), key=itemgetter(1))
OrderedDictPre-Python 3.7 compatibilityOrderedDict(sorted(d.items(), key=...))

By following these steps, you can efficiently sort dictionaries by their values in Python!

Leave a Reply

Your email address will not be published. Required fields are marked *