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


The program imports the "operator" module and creates a dictionary d containing key-value pairs. Then, the dictionary is sorted in ascending order and stored in the variable sd. The sorted function takes two arguments: d.items() which returns a list of tuple pairs from the dictionary, and key=operator.itemgetter(1), which specifies that the values (the second item in each tuple pair) should be used as the sort key. Finally, the dictionary is sorted in descending order and stored in the same variable sd. The sorted function is called again with the added argument reverse=True, which sorts the list in reverse order. Both the sorted dictionaries are then printed to show the result.

Source Code

import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
print('Original dictionary : ',d)
sd = sorted(d.items(), key=operator.itemgetter(1))
print('Ascending order : ',sd)
sd = dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True))
print('Descending order : ',sd)

Output


Original dictionary :  {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
Ascending order :  [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
Descending order :  {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}