How to Sort Dictionary by Key in Python: Simple Guide
To sort a dictionary by key in Python, use the
sorted() function on the dictionary's keys and create a new dictionary from the sorted keys. This can be done simply with sorted_dict = {k: original_dict[k] for k in sorted(original_dict)}.Syntax
Use the sorted() function on the dictionary keys to get them in order. Then, create a new dictionary by looping over these sorted keys.
sorted(dict): Returns a list of keys sorted in ascending order.{k: dict[k] for k in sorted(dict)}: Dictionary comprehension to build a new dictionary with keys in sorted order.
python
sorted_dict = {k: original_dict[k] for k in sorted(original_dict)}Example
This example shows how to sort a dictionary by its keys and print the sorted dictionary.
python
original_dict = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
sorted_dict = {k: original_dict[k] for k in sorted(original_dict)}
print(sorted_dict)Output
{'apple': 4, 'banana': 3, 'orange': 2, 'pear': 1}
Common Pitfalls
One common mistake is trying to sort the dictionary directly, which does not work because dictionaries are unordered collections (before Python 3.7) or maintain insertion order (Python 3.7+), but do not sort themselves.
Another mistake is using dict.sort(), which is invalid because dictionaries do not have a sort() method.
Always use sorted() on keys or items and build a new dictionary.
python
wrong = {'banana': 3, 'apple': 4}
# wrong.sort() # This will cause an AttributeError
# Correct way:
sorted_dict = {k: wrong[k] for k in sorted(wrong)}
print(sorted_dict)Output
{'apple': 4, 'banana': 3}
Quick Reference
- sorted(dict): Returns sorted keys list.
- {k: dict[k] for k in sorted(dict)}: Creates sorted dictionary by keys.
- Dictionaries keep insertion order (Python 3.7+), so new dict is sorted.
Key Takeaways
Use sorted() on dictionary keys to get them in order.
Create a new dictionary with sorted keys using dictionary comprehension.
Dictionaries do not have a sort() method; sorting must be done externally.
From Python 3.7+, dictionaries keep insertion order, so new dict preserves sorted order.
Always build a new dictionary to get a sorted version by keys.