Junior
How to sort a dictionary by keys in alphabetical order?
sobes.tech AI
Answer from AI
To sort a dictionary by keys in alphabetical order, you can use the sorted() function applied to the dictionary's keys, and then create a new sorted dictionary.
# Original dictionary
my_dict = {'b': 2, 'a': 1, 'd': 4, 'c': 3}
# Get sorted keys
sorted_keys = sorted(my_dict.keys())
# Create a new dictionary using the sorted keys
sorted_dict = {key: my_dict[key] for key in sorted_keys}
# Print the sorted dictionary
print(sorted_dict)
Another way is to use the sorted() method directly on the dictionary items, specifying a key for sorting.
# Original dictionary
my_dict = {'b': 2, 'a': 1, 'd': 4, 'c': 3}
# Sort items (key-value pairs) by keys
sorted_items = sorted(my_dict.items())
# Create a new dictionary from the sorted items
sorted_dict = dict(sorted_items)
# Print the sorted dictionary
print(sorted_dict)
Both methods create a new dictionary, as dictionaries in Python versions before 3.7 were unordered by nature. In Python 3.7+, dictionaries preserve insertion order, so you can get a sorted view, but the original dictionary remains unchanged.
| Method | Description | Result |
|---|---|---|
sorted(my_dict.keys()) |
Get a list of sorted keys and create a new dictionary. | A new dictionary with sorted keys. |
sorted(my_dict.items()) |
Get a list of (key, value) pairs, sort by key, and create a new dictionary. | A new dictionary with sorted keys. |