Member-only story
How to Sort a Dictionary by Key in Python
Sorting a dictionary by key is a common task in Python, especially when presenting data in a more structured or readable format. While dictionaries are inherently unordered in older Python versions (before 3.7), modern Python guarantees that they maintain insertion order. Sorting a dictionary can help with data such as configurations, statistics, or even logs.
This post will explore how to sort a dictionary by its keys, showcase different methods, and cover edge cases.
Read the full story here: https://allwin-raju-12.medium.com/how-to-sort-a-dictionary-by-key-in-python-6a3df0786612?sk=e873cd9a6740d030fb7c52c7604463da
Basic Method: Using sorted()
The simplest way to sort a dictionary by its keys is to use Python’s built-in sorted()
function.
Example:
my_dict = {"b": 2, "a": 1, "c": 3}
# Sorting the dictionary by key
sorted_dict = dict(sorted(my_dict.items()))
print(sorted_dict)
Output:
{'a': 1, 'b': 2, 'c': 3}
Explanation:
my_dict.items()
: Converts the dictionary into a sequence of(key, value)
tuples.sorted()
: Sorts these tuples by key (default for tuple sorting).