Last modified: Jan 27, 2026 By Alexander Williams
Python Sort Dictionary by Keys: A Complete Guide
Python dictionaries are powerful data structures. They store data as key-value pairs. However, dictionaries are inherently unordered in Python versions before 3.7. From Python 3.7 onward, they maintain insertion order. But what if you need a specific order, like alphabetical or numerical, based on the keys? This guide will show you how.
You cannot use a sort() method directly on a dictionary. Trying to do so results in an AttributeError. This is a common hurdle for beginners. Instead, you must use other techniques to create a sorted representation of your dictionary's contents.
This article covers three main methods. We will use the sorted() function, dictionary comprehension, and the collections.OrderedDict class. Each method has its use case. We will explain them with clear examples.
Why Sort a Dictionary by Keys?
Sorting a dictionary can be crucial for many tasks. You might need to display data in a predictable order. Logging, reporting, and data presentation often require sorted keys. It also helps in debugging by providing consistent output.
For instance, you might have a dictionary of country codes and names. Presenting them alphabetically by code makes the data much more usable. Or, you might have numerical IDs as keys that need to be in sequence.
Remember, if you are using Python 3.6 or earlier, dictionaries do not preserve any order. Even in later versions, the preserved order is insertion order, not sorted order. So, explicit sorting is necessary.
Method 1: Using the sorted() Function
The built-in sorted() function is the most common tool for this job. It returns a new sorted list from the items of any iterable. When applied to a dictionary, it iterates over the keys by default.
The basic approach is to get a sorted list of keys, then rebuild the dictionary. However, since Python 3.7, you can directly create a new dictionary from the sorted key-value pairs.
Let's look at a simple example. We will sort a dictionary with string keys.
# Original dictionary with unsorted keys
student_grades = {
"Charlie": 85,
"Alice": 92,
"Bob": 78,
"David": 88
}
# Get a sorted list of the keys
sorted_keys = sorted(student_grades)
print("Sorted keys:", sorted_keys)
# Create a new dictionary by iterating through sorted keys
sorted_dict = {}
for key in sorted_keys:
sorted_dict[key] = student_grades[key]
print("Sorted dictionary:", sorted_dict)
Sorted keys: ['Alice', 'Bob', 'Charlie', 'David']
Sorted dictionary: {'Alice': 92, 'Bob': 78, 'Charlie': 85, 'David': 88}
The sorted() function sorted the keys alphabetically. We then built a new dictionary using a for loop. The new dictionary, sorted_dict, has its items in alphabetical key order.
Method 2: Using Dictionary Comprehension
Dictionary comprehension offers a more concise and "Pythonic" way. It combines the sorting and rebuilding steps into a single, readable line. This is often the preferred method in modern Python code.
The syntax is straightforward. You use sorted(dict.items()) to get a list of (key, value) tuples in order. Then, you feed this into a comprehension to create the new dictionary.
# Original dictionary
inventory = {
105: "monitor",
102: "keyboard",
101: "mouse",
104: "cable",
103: "headphones"
}
# Sort by key using dictionary comprehension
sorted_inventory = {k: inventory[k] for k in sorted(inventory)}
print("Sorted by key (comprehension):", sorted_inventory)
# Alternative: Sort by key using dict() and sorted items
sorted_inventory_v2 = dict(sorted(inventory.items()))
print("Sorted by key (dict()):", sorted_inventory_v2)
Sorted by key (comprehension): {101: 'mouse', 102: 'keyboard', 103: 'headphones', 104: 'cable', 105: 'monitor'}
Sorted by key (dict()): {101: 'mouse', 102: 'keyboard', 103: 'headphones', 104: 'cable', 105: 'monitor'}
Both lines produce the same result. The numerical keys are now in ascending order. The dict() constructor method is very clean and readable. It is a great choice for this task. For more on building dictionaries, see our Python Dict Literal Guide & Examples.
Method 3: Using collections.OrderedDict
Before Python 3.7, the collections.OrderedDict class was essential for maintaining order. While less critical now, it still clearly signals intent. It is a dictionary subclass that remembers the order entries were added.
You create an OrderedDict from the sorted list of items. The order is then fixed and will be maintained through all standard operations.
from collections import OrderedDict
config = {
"z_port": 8080,
"a_host": "localhost",
"m_debug": True,
"c_timeout": 30
}
# Create an OrderedDict from items sorted by key
ordered_config = OrderedDict(sorted(config.items()))
print("OrderedDict by keys:", ordered_config)
print("Type:", type(ordered_config))
OrderedDict by keys: OrderedDict([('a_host', 'localhost'), ('c_timeout', 30), ('m_debug', True), ('z_port', 8080)])
Type: The keys are sorted alphabetically. The OrderedDict behaves like a regular dictionary but guarantees order. This can be useful for older codebases or when order is a critical contract. To understand other dictionary behaviors, our Python Dictionary Keys: Guide & Examples is a helpful resource.
Custom Sorting and Reverse Order
The sorted() function is versatile. You can sort in descending order using the reverse=True argument. You can also provide a custom sorting key using the key argument, though for simple keys this is often not needed.
data = {"apple": 5, "Orange": 3, "banana": 7, "kiwi": 1}
# Sort keys in reverse (descending) alphabetical order
sorted_desc = dict(sorted(data.items(), reverse=True))
print("Descending order:", sorted_desc)
# Sort keys case-insensitively
sorted_insensitive = dict(sorted(data.items(), key=lambda item: item[0].lower()))
print("Case-insensitive sort:", sorted_insensitive)
Descending order: {'orange': 3, 'kiwi': 1, 'banana': 7, 'apple': 5}
Case-insensitive sort: {'apple': 5, 'banana': 7, 'kiwi': 1, 'Orange': 3}
These examples show the flexibility of the sorting process. The key function allows for complex sorting logic, such as case-insensitive comparison.
Important Considerations and Best Practices
Dictionaries are not lists. The concept of "sorting in-place" doesn't apply to standard dictionaries. You always create a new dictionary object. The original dictionary remains unchanged.
Performance is generally good. The sorted() function uses the Timsort algorithm, which is efficient. For very large dictionaries, consider if sorting is absolutely necessary for your task.
Remember that sorting is based on the keys. If you need to sort by values, the process is different. You would use sorted(dict.items(), key=lambda item: item[1]).
Always check if your dictionary has data before sorting. Sorting an empty dictionary is pointless but harmless. You can learn how to Check if Python Dictionary is Empty first.
Conclusion
Sorting a Python dictionary by its keys is a fundamental skill. The primary method is using the sorted() function with dict() or a dictionary comprehension. For Python 3.7+, the resulting dictionary will maintain this sorted order.
Use dict(sorted(my_dict.items())) for a clean, one-line solution. Use OrderedDict if you need explicit order guarantees or are supporting older Python versions.
The key takeaway is that you transform the dictionary into a sorted list of tuples and then create a new mapping. With these techniques, you can easily organize your dictionary data for display, processing, or output.