Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to sort a dictionary in Python by keys?
Python allows dictionaries to be sorted using the built-in sorted() function. Although dictionaries in Python 3.7+ preserve insertion order, we can still create a new dictionary sorted by its keys using various methods.
In this article, we will explore different ways to sort a dictionary in Python by its keys.
Using sorted() with Dictionary Comprehension
The most Pythonic way to sort a dictionary by keys is using dictionary comprehension with the sorted() function. This creates a new dictionary with keys in alphabetical order ?
data = {
'zebra': 26,
'apple': 1,
'dog': 4,
'cat': 3
}
# Sort dictionary by keys using comprehension
sorted_dict = {key: data[key] for key in sorted(data)}
print("Original:", data)
print("Sorted: ", sorted_dict)
Original: {'zebra': 26, 'apple': 1, 'dog': 4, 'cat': 3}
Sorted: {'apple': 1, 'cat': 3, 'dog': 4, 'zebra': 26}
Using sorted() with a Loop
You can also iterate through sorted keys to build a new dictionary manually ?
data = {
'banana': 2,
'apple': 1,
'cherry': 3
}
# Create new dictionary by iterating sorted keys
sorted_dict = {}
for key in sorted(data.keys()):
sorted_dict[key] = data[key]
print("Sorted dictionary:", sorted_dict)
Sorted dictionary: {'apple': 1, 'banana': 2, 'cherry': 3}
Sorting in Reverse Order
To sort keys in descending order, use the reverse=True parameter ?
scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'Diana': 96}
# Sort in reverse (descending) order
reverse_sorted = {key: scores[key] for key in sorted(scores, reverse=True)}
print("Reverse sorted:", reverse_sorted)
Reverse sorted: {'Diana': 96, 'Charlie': 78, 'Bob': 92, 'Alice': 85}
Using collections.OrderedDict
While regular dictionaries maintain order in Python 3.7+, you can use OrderedDict for explicit order management ?
from collections import OrderedDict
data = {'delta': 4, 'alpha': 1, 'gamma': 3, 'beta': 2}
# Sort using OrderedDict
sorted_ordered = OrderedDict(sorted(data.items()))
print("OrderedDict result:", sorted_ordered)
print("Type:", type(sorted_ordered))
OrderedDict result: OrderedDict([('alpha', 1), ('beta', 2), ('gamma', 3), ('delta', 4)])
Type: <class 'collections.OrderedDict'>
Comparison of Methods
| Method | Performance | Readability | Return Type |
|---|---|---|---|
| Dictionary Comprehension | Fast | High | dict |
| Loop Method | Slower | Medium | dict |
| OrderedDict | Fast | Medium | OrderedDict |
Conclusion
Dictionary comprehension with sorted() is the most efficient and Pythonic way to sort dictionaries by keys. Use reverse=True for descending order, and consider OrderedDict when you need explicit order guarantees.
