Search your course

 

 

How to Sort Dictionary using keys or values in python


 

As there is no such method as .sort() or sorted() to sort dictionary so lets apply some logic,

Below code can be used to sort dictionary on basis of keys

 

dictionary = {1:2 , 4:3 , 3:4 , 0:0 , 2:1}
print({x: y for x, y in sorted(dictionary.items(), key=lambda item: item[0])})

 

and to sort dictionary on basis of values, copy following lines of code into your script

 

dictionary = {1:2 , 4:3 , 3:4 , 0:0 , 2:1}
print({x: y for x, y in sorted(dictionary.items(), key=lambda item: item[1])})

 

Subscribe to my youtube channel