Sort dictionary in Python
Python dictionary stores data in key-value pairs. In some situations, programmers need to sort the dictionary object as per their requirement which may be based on key or value. To sort dictionary object, you can user sorted() method and pass either keys or values from the dictionary which sorts the elements in their natural order. For example, if the elements are all integers, then smaller numbers go earlier in the list. If the elements are all strings, they are arranged in alphabetic order. Below examples demonstrate different ways to sort the dictionary based on key or value.
1) Sort dictionary based on keys
1 2 3 4 5 |
if __name__ == '__main__': #dictionary containing number of users in different languages languages = {'Python': 93, 'Java': 95, 'C': 91, 'C++':92} for key in sorted(languages.keys()) : print('%s : %s' %(key, languages[key])) |
Output
1 2 3 4 |
C : 91 C++ : 92 Java : 95 Python : 93 |
2) Sort dictionary based on keys in descending order
1 2 3 4 5 |
if __name__ == '__main__': #dictionary containing number of users in different languages languages = {'Python': 93, 'Java': 95, 'C': 91, 'C++':92} for key in sorted(languages.keys(), reverse=True) : print('%s : %s' %(key, languages[key])) |
Output
1 2 3 4 |
Python : 93 Java : 95 C++ : 92 C : 91 |
3) Sort dictionary based on values
1 2 3 4 5 |
if __name__ == '__main__': #dictionary containing number of users in different languages languages = {'Python': 93, 'Java': 95, 'C': 91, 'C++':92} for key, value in sorted(languages.items(), key=lambda x:x[1]) : print('%s : %s' %(key, value)) |
Output
1 2 3 4 |
C : 91 C++ : 92 Python : 93 Java : 95 |
4) Sort dictionary based on values in descending order
1 2 3 4 5 |
if __name__ == '__main__': #dictionary containing number of users in different languages languages = {'Python': 93, 'Java': 95, 'C': 91, 'C++':92} for key, value in sorted(languages.items(), key=lambda x:x[1], reverse=True): print('%s : %s' %(key, value)) |
Output
1 2 3 4 |
Java : 95 Python : 93 C++ : 92 C : 91 |
Stay tuned for more updates and tutorials !!!