Sort a dictionary by value in Python
This post will discuss how to sort a dictionary by its value in Python.
The Python Dictionaries before version 3.7 are unordered. That means even if you sort the dictionary, you can’t store it in a way that preserves the ordering.
1. Using collections.OrderedDict
The idea is to pass the dictionary’s items to the sorted() function, which returns a sorted list of dictionary entries using the specified key. Then you insert the sorted entries into collections.OrderedDict, which remembers the insertion order.
|
1 2 3 4 5 6 7 8 9 10 11 |
import operator if __name__ == '__main__': d = {"three": 3, "two": 2, "four": 4, "one": 1} sortedDictWithValues = dict(sorted(d.items(), key=operator.itemgetter(1))) # {'one': 1, 'two': 2, 'three': 3, 'four': 4} print(sortedDictWithValues) |
In Python 3, you can sort the list of tuples by the second element in each tuple as follows:
|
1 2 3 4 5 6 7 8 9 10 11 |
import collections if __name__ == '__main__': d = {"three": 3, "two": 2, "four": 4, "one": 1} sortedDictWithValues = collections.OrderedDict(sorted(d.items(), key=lambda x: x[1])) # OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4)]) print(sortedDictWithValues) |
2. Python 3.7+
Before Python 3.7, it was not possible to sort a dictionary. You can use it only to get a sorted representation of a dictionary. With Python 3.7 or CPython 3.6+, the insertion order is now guaranteed in a dictionary. The following example demonstrates.
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': d = {"three": 3, "two": 2, "four": 4, "one": 1} sortedDictWithValues = dict(sorted(d.items(), key=lambda x: x[1])) # {'one': 1, 'two': 2, 'three': 3, 'four': 4} print(sortedDictWithValues) |
To sort it in reverse order, you can pass the reverse argument as True:
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': d = {"three": 3, "two": 2, "four": 4, "one": 1} sortedDictWithValues = dict(sorted(d.items(), key=lambda x: x[1], reverse=True)) # {'four': 4, 'three': 3, 'two': 2, 'one': 1} print(sortedDictWithValues) |
3. Using collections.Counter class
If the dictionary’s values are numeric, you can use the collections.Counter class to print a dictionary in decreasing order of their values.
|
1 2 3 4 5 6 7 8 9 10 11 |
from collections import Counter if __name__ == '__main__': d = {'three': 3, 'two': 2, 'four': 4, 'one': 1} c = Counter(d) # [('four', 4), ('three', 3), ('two', 2), ('one', 1)] print(c.most_common()) |
That’s all about sorting a dictionary by value 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 :)