How do I sort a dictionary by key?
In Python, dictionaries are unordered collections of key-value pairs.
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:
Sort a dictionary by keys in Python by sorting the keys array
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 3Alternatively, you can use the items() method of the dictionary along with the sorted() function, like so:
Sort a dictionary by keys in Python by sorting the items array
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.
Sort a dictionary by values in Python
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 3Additionally, python 3.7 and above you can use the dict() constructor and pass an ordered dict, to create a dict sorted by key
Sort a dictionary by in Python 3.7 or above using the dict constructor
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.