Sort a Dictionary by Key in Python

Python version 3.7 and later preserve insertion order, making it possible to sort a dictionary. However, versions earlier than 3.7 do not maintain this order, so sorting a dictionary won’t preserve the order. That’s why you should use collections.OrderedDict for Python versions earlier than 3.7.

You can sort a dictionary by key using the following methods:

(1) Using the sorted() function

You can use the built-in sorted() function to sort a dictionary by key.

For example:

my_dict = {'d':4, 'a': 1, 'c': 3, 'b': 2}

sorted_dict = dict(sorted(my_dict.items()))
print(sorted_dict)

Output:

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Explanation:

my_dict.items() returns a view of the dictionary’s key-value pairs as tuples in a list.

sorted(my_dict.items() sorts these tuples by the keys (the first element of each tuple) in ascending order.

dict(...) converts the sorted list of tuples back into a dictionary.

(2) Using collections.OrderedDict

If you are using a Python version earlier than 3.7 and want to preserve the order, you can use collections.OrderedDict.

For example:

from collections import OrderedDict

my_dict = {'d':4, 'a': 1, 'c': 3, 'b': 2}

sorted_dict = OrderedDict(sorted(my_dict.items()))
print(sorted_dict)

Output:

OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4})

(3) Sorting in descending order

If you want to sort a dictionary in descending order, you can set the reverse parameter of the sorted() function to True.

For example:

my_dict = {'d':4, 'a': 1, 'c': 3, 'b': 2}

sorted_dict = dict(sorted(my_dict.items(), reverse=True))
print(sorted_dict)

Output:

{'d': 4, 'c': 3, 'b': 2, 'a': 1}

(4) Case-insensitive sorting

To sort a dictionary by key in a case-insensitive manner, you can use str.lower() as the key function inside sorted() function to convert the keys to lowercase before conversion.

For example:

from collections import OrderedDict

my_dict = {'D':4, 'a': 1, 'c': 3, 'B': 2}

sorted_dict = dict(sorted(my_dict.items(), key=lambda x:x[0].lower()))
print(sorted_dict)

Output:

{'a': 1, 'B': 2, 'c': 3, 'D': 4}