HOW TO SORT DICTIONARY IN PYTHON

A Python dictionary is a data structure, which stores values as key-value pair. A dictionary has got very much importance in programming. Sorting a dictionary is one of those problems we encounter in many programming cases.
This can be done by using the built-in function sorted()
.
- Sorting by keys:
The sorted() function will take any iterable and returns the sorted list. To sort the dictionary by keys, pass key values to the sorted().
d = {1:'red', 4:'green', 2:'blue', 8:'black', 6:'yellow'} #sort the keys print(sorted(d.keys())) print(sorted(d.items()))
Output:
[1, 2, 4, 6, 8] [(1, 'red'), (2, 'blue'), (4, 'green'), (6, 'yellow'), (8, 'black')]
- Sorting by values:
Just like how we sorted dictionary using keys, we can sort by values.
d = {1:'red', 4:'green', 2:'blue', 8:'black', 6:'yellow'} print(sorted(d.values()))
Output:
['black', 'blue', 'green', 'red', 'yellow']
- Sorting the Keys and Values in alphabetical using the value
Od = {1:'red', 4:'green', 2:'blue', 8:'black', 6:'yellow'} print("Sorted by key: ",sorted(d.items(), key=lambda x:x[0])) print("Sorted by value: ",sorted(d.items(), key=lambda x:x[1]))
Output:
Sorted by key: [(1, 'red'), (2, 'blue'), (4, 'green'), (6, 'yellow'), (8, 'black')] Sorted by value: [(8, 'black'), (2, 'blue'), (4, 'green'), (1, 'red'), (6, 'yellow')]
- Reverse:
The default sorting order is ascending. In case we want the descending order, we can use reverse=True
.
d = {1:'red', 4:'green', 2:'blue', 8:'black', 6:'yellow'} print(sorted(d.keys(), reverse=True))
Output:
[8, 6, 4, 2, 1]
Subscribe
Login
Please login to comment
0 Discussion