w3resource logo


Python Exercises

Python Exercise: Program to sort a dictionary by value


Write a Python program to sort (ascending and descending) a dictionary by value.

Sample Solution :

Python Code :

  1. import operator  
  2. d = {1234432100}  
  3. print('Original dictionary : ',d)  
  4. sorted_d = sorted(d.items(), key=operator.itemgetter(0))  
  5. print('Dictionary in ascending order by value : ',sorted_d)  
  6. sorted_d = sorted(d.items(), key=operator.itemgetter(0),reverse=True)  
  7. print('Dictionary in descending order by value : ',sorted_d)  

Console :

Copy and paste the above code and press "Enter key" to execute :

Post your code through Disqus