How do I sort a dictionary by key?
How can you sort a dictionary by its keys in Python efficiently? Sorting by keys helps organize data for easier access, display, or further processing in a structured and readable way.
Sorting a dictionary by its keys in Python is a common task when you want your data to be organized, readable, or ready for further processing. Python dictionaries are inherently unordered in versions before 3.7, but from Python 3.7 onwards, they maintain insertion order. To sort a dictionary by keys, you can use several approaches.
Using sorted() with dictionary keys:
my_dict = {"banana": 3, "apple": 5, "cherry": 2}
sorted_dict = {k: my_dict[k] for k in sorted(my_dict.keys())}
print(sorted_dict)
# Output: {'apple': 5, 'banana': 3, 'cherry': 2}
Here, sorted(my_dict.keys()) returns a list of keys in ascending order, and a dictionary comprehension creates a new dictionary with the keys in that order.
Key points to remember:
- Ascending order: sorted() sorts keys alphabetically or numerically by default.
- Descending order: Use sorted(my_dict.keys(), reverse=True) to sort in reverse.
- Original dictionary remains unchanged: Sorting produces a new dictionary.
- Works with complex keys: You can provide a custom key function to sorted() if your keys need special sorting logic.
Example with descending order:
sorted_dict_desc = {k: my_dict[k] for k in sorted(my_dict.keys(), reverse=True)}
print(sorted_dict_desc)
# Output: {'cherry': 2, 'banana': 3, 'apple': 5}
Sorting a dictionary by keys is especially useful for displaying data in reports, exporting structured information, or simply making dictionaries easier to read. By using sorted() with dictionary comprehension, you get a clean and efficient way to organize your dictionary without modifying the original data.