In: Computer Science
In Python write a function with prototype “def dictsort(d):” which will return a list of key-value pairs of the dictionary as tuples (key, value), reverse sorted by value (highest first) and where multiple keys with the same value appear alphabetically (lowest first).
Below is a screen shot of the python program to check indentation. Comments are given on every line explaining the code. Below is the output of the program: Below is the code to copy: #CODE STARTS HERE----------------
from operator import itemgetter def dictsort(d): #Function that sorts a dictionary d_list = [] #List to store tuples for k,v in d.items(): #Convert dict to a list of tuples d_list.append((k,v))#Tuple is of the form (key, value) #First sort the "key" in alphabetic order d_list.sort(key=itemgetter(0)) #Then sort "value" in descending order d_list.sort(key = itemgetter(1), reverse=True) return d_list #Print result #Test case original_dict = {"d":5,"a":5,"f":5,"c":1,"p":8,"k":4} print("Original dict: ",original_dict) print("After sorting: ",dictsort(original_dict)) #Function call #CODE ENDS HERE------------------