How do I sort a dictionary by key?
In Python, dictionaries are unordered collections of key-value pairs. However, you can sort the keys of a dictionary and use them to iterate over the dictionary in a specific order.
Here's an example of how you can sort the keys of a dictionary and iterate over the key-value pairs in sorted order:
original_dict = {'c': 3, 'a': 1, 'b': 2}
# Sort the keys of the dictionary
sorted_keys = sorted(original_dict.keys())
# Iterate over the keys in sorted order
for key in sorted_keys:
print(key, original_dict[key])
This will output:
a 1 b 2 c 3
Alternatively, you can use the items()
method of the dictionary along with the sorted()
function, like so:
original_dict = {'c': 3, 'a': 1, 'b': 2}
for key, value in sorted(original_dict.items()):
print(key, value)
This will give you the same output as previous example.
If you want to sort the dictionary by the values instead, you can pass a key
function to the sorted()
function that retrieves the values from the tuple returned by items()
. You can also reverse the sorting order by passing reverse=True
as an argument to the sorted()
function.
original_dict = {'c': 3, 'a': 1, 'b': 2}
# Sort the dictionary by values and iterate over the items
for key, value in sorted(original_dict.items(), key=lambda item: item[1]):
print(key, value)
This will output:
a 1 b 2 c 3
Additionally, python 3.7 and above you can use the dict()
constructor and pass an ordered dict, to create a dict sorted by key
from collections.abc import MutableMapping
original_dict = {'c': 3, 'a': 1, 'b': 2}
sorted_dict = dict(sorted(original_dict.items()))
print(sorted_dict)
This will output:
{'a': 1, 'b': 2, 'c': 3}
Keep in mind that creating a new dictionary object means that the original dictionary is not modified.