w3resource

Python Exercise: Sort (ascending and descending) a dictionary by value

Python dictionary: Exercise-1 with Solution

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

Sample Solution:-

Python Code:

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

Sample Output:

Original dictionary :  {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
Dictionary in ascending order by value :  [(0, 0), (1, 2), (2, 1), (3, 4), (4, 3)]
Dictionary in descending order by value :  {4: 3, 3: 4, 2: 1, 1: 2, 0: 0} 

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Python Dictionary Exercise Home.
Next: Write a Python program to add a key to a dictionary.

What is the difficulty level of this exercise?



Inviting useful, relevant, well-written and unique guest posts