Write a program to sort dictionary by values (Ascending/ Descending)


The program defines a dictionary "d" which contains the marks of a student in 5 subjects (m1, m2, m3, m4, and m5).

  • The program uses the "sorted" function to sort the items in the dictionary in either ascending or descending order. The sorted function takes two arguments, the first argument being the list of items to sort and the second argument being the key to sort the items by.
  • The key to sort the items by is defined using the operator.itemgetter(1) function from the "operator" module. This function returns the value of the item in the tuple (i.e. the mark in this case).
  • For descending order, the sorted function is called with the reverse=True argument. This sorts the items in descending order. The sorted items are stored in the "des" variable and printed.
  • For ascending order, the sorted function is called without the reverse=True argument. This sorts the items in ascending order. The sorted items are stored in the "des" variable and printed.

In summary, the program sorts the marks of the student in ascending and descending order and prints the sorted results.

Source Code

import operator
d={"m1":78 , "m2":89 , "m3":64 , "m4":35 , "m5":71}
 
#Descending Order
des = sorted(d.items(),key=operator.itemgetter(1),reverse=True)
print("\nDescending Order :",des)
 
#Ascending Order
des = sorted(d.items(),key=operator.itemgetter(1))
print("\nAscending Order :",des)

Output

Descending Order : [('m2', 89), ('m1', 78), ('m5', 71), ('m3', 64), ('m4', 35)]

Ascending Order : [('m4', 35), ('m3', 64), ('m5', 71), ('m1', 78), ('m2', 89)]