Sort a dictionary by key in Python
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:
|
1 2 3 4 5 6 |
d = {'one': 1, 'two': 2, 'three': 3, 'four': 4} sortedDict = dict(sorted(d.items())) # {'four': 4, 'one': 1, 'three': 3, 'two': 2} print(sortedDict) |
To sort it in reverse order, we can pass the reverse argument as True:
|
1 2 3 4 5 6 |
d = {'one': 1, 'two': 2, 'three': 3, 'four': 4} sortedDict = dict(sorted(d.items(), reverse=True)) # {'two': 2, 'three': 3, 'one': 1, 'four': 4} print(sortedDict) |
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:
|
1 2 3 4 5 6 7 8 |
import collections d = {'one': 1, 'two': 2, 'three': 3, 'four': 4} sortedDict = collections.OrderedDict(sorted(d.items())) # OrderedDict([('four', 4), ('one', 1), ('three', 3), ('two', 2)]) print(sortedDict) |
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:
|
1 2 3 4 5 6 |
import json d = {'one': 1, 'two': 2, 'three': 3, 'four': 4} # {"four": 4, "one": 1, "three": 3, "two": 2} print(json.dumps(d, sort_keys=True)) |
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:
|
1 2 3 4 5 6 |
import pprint d = {'one': 1, 'two': 2, 'three': 3, 'four': 4} # {'four': 4, 'one': 1, 'three': 3, 'two': 2} pprint.pprint(d) |
That’s all about sorting a dictionary by key in Python.
Also See:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)