
Problem –
You want to sort a python dictionary by it’s key or value.
Solution –
Let’s create a dictionary first.
In [1]: person = {'Mike': 20, 'Eleven': 19, 'Will': 18, 'Dustin': 16}
Sort a Python Dictionary by Key –
We can sort a dictionary by the sorted function and dictionary comprehension.
The sorted function will sort the dictionary by key but it will return a list of tuples.
In [2]: sorted(person.items())
Out[2]: [('Dustin', 16), ('Eleven', 19), ('Mike', 20), ('Will', 18)]
Now, we can use a dictionary comprehension to convert it into a dictionary.
In [3]: sortedByKey = {k : v for k, v in sorted(person.items())}
In [4]: sortedByKey
Out[4]: {'Dustin': 16, 'Eleven': 19, 'Mike': 20, 'Will': 18}
To sort the dictionary by key in descending order we can use the reverse=True parameter.
In [5]: sortedByKey = {k : v for k, v in sorted(person.items(), reverse=True)}
In [6]: sortedByKey
Out[6]: {'Will': 18, 'Mike': 20, 'Eleven': 19, 'Dustin': 16}
Sort a Python Dictionary By Value –
To sort a dictionary by value we can use the key parameter in sorted function and use a lambda function.
In [7]: sortedByValue = {k : v for k, v in sorted(person.items(), key = lambda v: v[1]) }
In [8]: sortedByValue
Out[8]: {'Dustin': 16, 'Will': 18, 'Eleven': 19, 'Mike': 20}
In key = lambda v : v[1] , we are telling python to sort by the values.
To sort the dictionary by value in descending order we can again use the reverse=True parameter.
In [9]: sortedByValue = {k : v for k, v in sorted(person.items(), key = lambda v: v[1], reverse=True) }
In [10]: sortedByValue
Out[10]: {'Mike': 20, 'Eleven': 19, 'Will': 18, 'Dustin': 16}