This post will discuss how to sort a dictionary by its key in Python.

1. Using dictionary constructor

With Python 3.7 or CPython 3.6+, the dictionary order is the same as the insertion order. Therefore, we can get a sorted list of key-value pairs by passing the dictionary to the sorted() function. We can then use the dictionary constructor to get a new dictionary with those key-value pairs. We can see this behavior below:

Download  Run Code

 
To sort it in reverse order, we can pass the reverse argument as True:

Download  Run Code

2. Using collections.OrderedDict() class

Since dictionaries were unordered in Python before version 3.7, we couldn’t store them in a way that preserved the ordering. However, we can get a sorted list of key-value pairs by passing the dictionary’s items to the sorted() function. Then we can insert the entries of the sorted dictionary into an OrderedDict, which is a subclass of the dict class that remembers the order of the items. For example:

Download  Run Code

3. Using json.dumps() function

Another option is to pass our dictionary to the json.dumps() function with the sort_keys argument as True. Note that this returns the string representation of a sorted dictionary. Here is how we can use this function:

Download  Run Code

4. Using pprint.pprint() function

To print the sorted representation of a dictionary, we can use the pprint.pprint() function. It prints the dictionary in sorted key order. For example:

Download  Run Code

That’s all about sorting a dictionary by key in Python.

 
Also See:

Sort a dictionary by value in Python