Question
How can I sort a Python dictionary by its keys?
For example, given this dictionary:
numbers = {2: 3, 1: 89, 4: 5, 3: 0}
I want a dictionary whose items appear in ascending key order:
{1: 89, 2: 3, 3: 0, 4: 5}
Short Answer
You will learn how Python dictionaries store key-value pairs, how sorted() orders dictionary keys, and how to build a new dictionary with items inserted in sorted key order. You will also learn when sorting a dictionary is useful and when sorting only its keys is enough.
Concept
A Python dictionary maps keys to values. For example, in {2: 3}, 2 is the key and 3 is its associated value.
To sort a dictionary by key, first sort its keys, then create a new dictionary in that order:
numbers = {2: 3, 1: 89, 4: 5, 3: 0}
sorted_numbers = dict(sorted(numbers.items()))
numbers.items() produces key-value pairs such as (2, 3) and (1, 89). By default, sorted() compares the first element of each pair, which is the key. Finally, dict(...) builds a dictionary from those sorted pairs.
In modern Python (3.7+), dictionaries preserve insertion order. Therefore, the newly created dictionary keeps the sorted order when you print it or iterate over it.
Sorting matters when you need predictable output: reports, exported files, logs, test results, or user-facing lists. It does not change the relationship between a key and its value; it only changes the order in which items are stored and displayed.
Mental Model
Think of a dictionary as a set of labelled drawers:
- The key is the label on a drawer.
- The value is what is inside it.
Your drawers may have been added in a random order: 2, 1, 4, 3. Sorting by key means arranging the drawers by their labels: 1, 2, 3, 4.
The contents stay with the same drawer. Sorting {2: 3, 1: 89} never changes it into {1: 3, 2: 89}. Instead, it becomes {1: 89, 2: 3} because each value remains attached to its original key.
Syntax and Examples
The most common approach is:
sorted_dictionary = dict(sorted(original_dictionary.items()))
Example:
numbers = {2: 3, 1: 89, 4: 5, 3: 0}
sorted_numbers = dict(sorted(numbers.items()))
print(sorted_numbers)
Output:
{1: 89, 2: 3, 3: 0, 4: 5}
Sort in descending key order
Pass reverse=True to sorted():
numbers = {2: 3, 1: 89, 4: 5, 3: 0}
largest_key_first = ((numbers.items(), reverse=))
(largest_key_first)
Step by Step Execution
Consider this code:
numbers = {2: 3, 1: 89, 4: 5, 3: 0}
result = dict(sorted(numbers.items()))
Here is what happens:
-
numbers.items()creates a view of the dictionary's pairs:dict_items([(2, 3), (1, 89), (4, 5), (3, 0)]) -
sorted(...)sorts these pairs. Since no custom sorting rule was provided, Python compares the first part of each pair: the keys.[(1, 89), (2, 3), (3, 0), (4, 5)] -
dict(...)turns the sorted list of pairs back into a dictionary.
Real World Use Cases
Sorting dictionary keys is useful whenever output should be stable and easy to read.
- Configuration output: Display configuration options alphabetically so users can find settings quickly.
- API responses: Produce predictable JSON-like data for documentation, debugging, or snapshots.
- Reports: List sales totals by product code, date, or region in a meaningful order.
- Data exports: Write dictionary data to a text or CSV file in a repeatable order.
- Testing: Avoid flaky text comparisons by sorting data before creating expected output.
- Logs and debugging: Print fields in a consistent order so two log entries are easier to compare.
Example: generating a simple report from scores:
scores = {102: 75, 101: 88, 103: 91}
for student_id in sorted(scores):
print(f"Student {student_id}: {scores[student_id]}")
Student 101: 88
Student 102: 75
Student 103: 91
Real Codebase Usage
In real projects, developers often avoid sorting until the moment it is needed. The original dictionary may be best kept in its natural insertion order, while a report or response is sorted at the boundary of the application.
Sort while rendering or exporting
settings = {"theme": "dark", "autosave": True, "font_size": 14}
for name, value in sorted(settings.items()):
print(f"{name}: {value}")
This is useful when displaying data but no later code requires a new sorted dictionary.
Return a sorted mapping from a helper function
def sorted_by_key(data):
return dict(sorted(data.items()))
status_codes = {500: "Server Error", 200: "OK", 404: "Not Found"}
print(sorted_by_key(status_codes))
Use a custom key for case-insensitive text
Normal string sorting places uppercase and lowercase letters according to Unicode ordering. For alphabetical sorting that ignores case, use key=str.lower:
Common Mistakes
Expecting sorted() to return a dictionary
sorted() always returns a list.
numbers = {2: 3, 1: 89}
result = sorted(numbers.items())
print(result)
# [(1, 89), (2, 3)]
If you need a dictionary, wrap the result in dict(...):
result = dict(sorted(numbers.items()))
Sorting values accidentally
This code sorts pairs by their values, not their keys:
numbers = {2: 3, 1: 89, 4: 5, 3: 0}
wrong_for_key_sorting = dict(sorted(numbers.items(), key=lambda item: item[1]))
Use sorted(numbers.items()) for the default ascending key sort.
Assuming the original dictionary is changed
Comparisons
| Approach | Result | Best use |
|---|---|---|
sorted(data) | A sorted list of keys | You only need keys in order. |
sorted(data.items()) | A sorted list of (key, value) tuples | You need ordered pairs but not a dictionary. |
dict(sorted(data.items())) | A new dictionary inserted in key order | You want an ordered dictionary result in Python 3.7+. |
sorted(data.items(), key=lambda item: item[1]) | Pairs sorted by value | You want to order items using values. |
sorted(data.items(), reverse=True) | Pairs in descending key order | You want largest or last keys first. |
Sorting by key versus sorting by value
Cheat Sheet
# Sort keys and create a new dictionary
ordered = dict(sorted(data.items()))
# Sort keys in descending order
ordered = dict(sorted(data.items(), reverse=True))
# Iterate through keys in ascending order
for key in sorted(data):
print(key, data[key])
# Get sorted key-value pairs as a list
pairs = sorted(data.items())
# Sort items by value instead of key
by_value = dict(sorted(data.items(), key=lambda item: item[1]))
# Sort string keys without considering case
case_insensitive = dict(
sorted(data.items(), key=lambda item: item[0].lower())
)
Key points:
sorted()returns a list.dict.items()provides(key, value)pairs.- Sorting pairs without a
key=argument sorts by key first. - Python 3.7+ dictionaries retain insertion order.
- The original dictionary is unchanged unless you assign the new result.
FAQ
Does Python sort dictionaries automatically?
No. A dictionary preserves the order in which items were inserted in Python 3.7+, but it does not automatically arrange keys alphabetically or numerically.
How do I sort a dictionary by key in Python?
Use dict(sorted(data.items())) to create a new dictionary with items inserted in ascending key order.
Can I use sorted(my_dict) instead of sorted(my_dict.items())?
Yes, but it returns only a list of sorted keys. Use it when iterating: for key in sorted(my_dict):.
Does sorting a dictionary modify the original dictionary?
No. sorted() creates a new list. Create and assign a new dictionary if you need to keep the sorted result.
How do I sort dictionary keys in reverse order?
Use dict(sorted(data.items(), reverse=True)).
Why does sorting my dictionary raise a TypeError?
Some keys cannot be compared with each other, such as an integer and a string in Python 3. Use one consistent key type or provide a meaningful custom sorting function.
Can I sort a dictionary by value instead?
Yes. Use dict(sorted(data.items(), key=lambda item: item[1])) to sort by each pair's value.
Is a sorted dictionary a different data type?
No. dict(sorted(data.items())) returns a normal . Its iteration order reflects the order in which sorted items were inserted.
Mini Project
Description
Build a small score report formatter. A program receives student IDs and scores in an arbitrary dictionary order, then prints a clear report ordered by student ID. This mirrors common tasks such as exporting records, producing reports, and generating stable output for tests.
Goal
Create a function that returns a score report with student records sorted by ID.
Requirements
Store at least four student ID-to-score pairs in a dictionary. Sort the records by student ID in ascending order. Print one formatted line for every student. Return the sorted dictionary from a function. Also demonstrate descending order in one additional output.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Add Rows to a Pandas DataFrame in Python
Learn how to add rows to a Pandas DataFrame, why repeated row appends are slow, and when to use loc, concat, or record lists.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.