I was working on a project where I needed to display U.S. state abbreviations in alphabetical order. The data was stored in a Python dictionary, but as you might know, dictionaries in Python don’t maintain any specific order by default.
While Python 3.7+ maintains insertion order, sometimes you still need to sort a dictionary by key for better readability, data presentation, or reporting.
In this tutorial, I’ll share several simple and efficient ways to sort a dictionary by key in Python, based on my 10+ years of experience working with Python data structures.
Sort a Dictionary by Key in Python
Sorting a dictionary by key can make your data easier to read and analyze. For example, if you’re working with a dataset of U.S. states and their populations, sorting them alphabetically by state name makes it much more intuitive to navigate.
Python provides several ways to achieve this, from using the built-in sorted() function to more advanced techniques like dictionary comprehensions or the collections module.
Method 1 – Use the sorted() Function with a For Loop
The simplest and most common way to sort a dictionary by key in Python is by using the sorted() function. The sorted() function returns a sorted list of the dictionary’s keys, which you can then use to create a new ordered dictionary.
Here’s how I do it in my projects:
# Example: Sorting a dictionary of US states by key (alphabetically)
us_states = {
"TX": "Texas",
"CA": "California",
"NY": "New York",
"FL": "Florida",
"IL": "Illinois"
}
# Sort dictionary by key using sorted()
sorted_states = {}
for key in sorted(us_states.keys()):
sorted_states[key] = us_states[key]
print("Original Dictionary:")
print(us_states)
print("\nSorted Dictionary by Key:")
print(sorted_states)I executed the above example code and added the screenshot below.

In this example, the dictionary us_states is sorted alphabetically by its keys (CA, FL, IL, NY, TX). This approach is simple, readable, and perfect for beginners who want to understand how sorting works internally in Python.
Method 2 – Use Dictionary Comprehension
If you prefer a more Pythonic way, you can use a dictionary comprehension to achieve the same result in a single line.
This method is concise and often used in data manipulation scripts or web applications where performance and readability matter.
Here’s the code:
# Sort dictionary by key using dictionary comprehension
us_states = {
"TX": "Texas",
"CA": "California",
"NY": "New York",
"FL": "Florida",
"IL": "Illinois"
}
sorted_states = {key: us_states[key] for key in sorted(us_states)}
print(sorted_states)I executed the above example code and added the screenshot below.

This one-liner uses sorted(us_states) to get the sorted list of keys and constructs a new dictionary in that order. I often use this approach when I’m cleaning or preparing data for visualization in tools like Matplotlib or Dash.
Method 3 – Use the dict() Constructor with sorted()
Another clean way to sort a Python dictionary by key is to combine the sorted() function with the dict() constructor.
This approach is ideal when you want to directly create a new dictionary from sorted key-value pairs without using loops or comprehensions.
Here’s how it works:
# Sort dictionary by key using dict() constructor
us_states = {
"TX": "Texas",
"CA": "California",
"NY": "New York",
"FL": "Florida",
"IL": "Illinois"
}
sorted_states = dict(sorted(us_states.items()))
print(sorted_states)I executed the above example code and added the screenshot below.

The sorted(us_states.items()) returns a list of tuples sorted by key, and then dict() converts it back into a dictionary.
This method is both elegant and efficient, and I often use it when I need to sort dictionaries before exporting them to JSON or CSV files.
Method 4 – Sort Dictionary by Key in Descending Order
Sometimes, you might want to sort your dictionary in reverse alphabetical order. Python makes this easy by using the reverse=True parameter in the sorted() function.
Here’s a quick example:
# Sort dictionary by key in descending order
us_states = {
"TX": "Texas",
"CA": "California",
"NY": "New York",
"FL": "Florida",
"IL": "Illinois"
}
sorted_states_desc = dict(sorted(us_states.items(), reverse=True))
print(sorted_states_desc)I executed the above example code and added the screenshot below.

In this example, the keys are sorted in descending order (TX, NY, IL, FL, CA). This method works great when you’re displaying data in dashboards or reports where reverse sorting provides better readability.
Method 5 – Use collections.OrderedDict
Before Python 3.7 introduced ordered dictionaries by default, the OrderedDict class from the collections module was the go-to solution.
Even today, it’s useful when you want to explicitly preserve the order of dictionary elements after sorting.
Here’s how I use it:
from collections import OrderedDict
# Sort dictionary by key using OrderedDict
us_states = {
"TX": "Texas",
"CA": "California",
"NY": "New York",
"FL": "Florida",
"IL": "Illinois"
}
sorted_states = OrderedDict(sorted(us_states.items()))
print(sorted_states)The OrderedDict ensures that the dictionary maintains its sorted order even if you perform further operations on it. This is especially helpful when working with configuration files, API responses, or serialized data that must retain order.
Method 6 – Sort Dictionary by Key Case-Insensitively
When working with real-world data, you might encounter keys with mixed cases, for example, “Texas”, “california”, “NEW YORK”.
To sort these keys case-insensitively, you can use the key=str.lower argument in the sorted() function.
Here’s how it’s done:
# Sort dictionary by key (case-insensitive)
us_states = {
"Texas": "TX",
"california": "CA",
"NEW YORK": "NY",
"florida": "FL",
"Illinois": "IL"
}
sorted_states = dict(sorted(us_states.items(), key=lambda x: x[0].lower()))
print(sorted_states)This method ensures that the sorting order is consistent, regardless of key capitalization. It’s particularly useful when processing user-input data or working with external datasets where capitalization may vary.
Method 7 – Sort Nested Dictionaries by Key
In more complex datasets, you might have nested dictionaries (dictionaries within dictionaries).
Let’s say you’re working with U.S. state data that includes population and area. You can sort the outer dictionary by state abbreviation, while keeping the inner dictionaries intact.
Here’s an example:
# Sort nested dictionary by key
us_data = {
"TX": {"population": 29145505, "area": 268596},
"CA": {"population": 39538223, "area": 163696},
"NY": {"population": 20201249, "area": 54555},
"FL": {"population": 21538187, "area": 65758},
"IL": {"population": 12812508, "area": 57914}
}
sorted_us_data = dict(sorted(us_data.items()))
print(sorted_us_data)This approach is extremely useful when you’re preparing structured data for APIs or data visualization libraries like Plotly or Seaborn.
Practical Use Case: Sorting JSON Data Before Export
When exporting data to JSON, sorting dictionary keys can make the output more structured and easier to read.
Here’s how I do it using the json module:
import json
# Sort dictionary before exporting to JSON
us_states = {
"TX": "Texas",
"CA": "California",
"NY": "New York",
"FL": "Florida",
"IL": "Illinois"
}
# Sort and export to JSON
with open("us_states_sorted.json", "w") as file:
json.dump(dict(sorted(us_states.items())), file, indent=4)This ensures your exported JSON file is alphabetically ordered by keys, a small but impactful improvement for readability.
Key Takeaways
- Use sorted() for simple sorting by key.
- Use dictionary comprehensions for concise one-liners.
- Use OrderedDict if you need explicit order preservation.
- Use key=str.lower for case-insensitive sorting.
- Combine with json.dump() for clean, sorted exports.
Sorting a dictionary by key in Python is a small but powerful skill that can make your code cleaner and your data easier to understand.
Whether you’re building data dashboards, generating reports, or cleaning large datasets, these methods will help you organize your Python dictionaries efficiently.
You may also like to read:
- Check If a File Exists and Create It If Not in Python
- Python Create File
- Call a Function from Another File in Python
- Get the Directory of a File in Python

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.