To sort a dictionary by its keys in Python, you can use the following approaches, depending on your Python version and requirements:
1. For Python 3.7+ (Standard dict
Preserves Insertion Order)
Convert the dictionary items to a sorted list of (key, value)
tuples and create a new dictionary:
my_dict = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
# Sort by keys and create a new dictionary
sorted_dict = dict(sorted(my_dict.items()))
print(sorted_dict)
# Output: {'apple': 4, 'banana': 3, 'orange': 2, 'pear': 1}
2. For Python <3.7 (Use collections.OrderedDict
)
Use OrderedDict
to maintain the sorted order:
from collections import OrderedDict
my_dict = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
# Sort by keys and create an OrderedDict
sorted_dict = OrderedDict(sorted(my_dict.items()))
print(sorted_dict)
# Output: OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
3. Return a Sorted List of Keys/Values (Without Creating a New Dict)
If you only need sorted keys or key-value pairs (not a dictionary):
# Sorted list of keys
sorted_keys = sorted(my_dict.keys())
# Sorted list of (key, value) tuples
sorted_items = sorted(my_dict.items())
4. Sort by Keys in Reverse Order
Add reverse=True
to sort in descending order:
sorted_dict = dict(sorted(my_dict.items(), reverse=True))
# Output: {'pear': 1, 'orange': 2, 'banana': 3, 'apple': 4}
Key Notes
- Immutability: Dictionaries cannot be sorted in-place. A new ordered dictionary is created.
- Custom Sorting: For complex keys (e.g., case-insensitive strings), use the
key
parameter:
# Case-insensitive sort for string keys
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[0].lower()))
- Efficiency: Sorting has a time complexity of
O(n log n)
, wheren
is the number of items.
Example Workflow
# Original dictionary
my_dict = {'b': 2, 'a': 1, 'c': 3}
# Sort and create a new dictionary
sorted_dict = dict(sorted(my_dict.items()))
print(sorted_dict) # {'a': 1, 'b': 2, 'c': 3}
Summary
- Python 3.7+: Use
dict(sorted(my_dict.items()))
. - Legacy Python: Use
OrderedDict(sorted(my_dict.items()))
. - Reverse Order: Add
reverse=True
to thesorted()
function.