Write a python program to accept the sorting  key from the user and display the sorted list of  rollno and marks of 40 students of a class stored  in a dictionary named score as key value pairs. 

 

Answer:

-lock-

# Ask the user how they want to sort the data (by rollno or marks)

sort_key = input("How do you want to sort the data? According to rollno or marks? ")

# Ask the user if they want to sort the list in ascending or descending order

order = input("Enter True if you want to sort the list in ascending order else enter False ")

# Convert the order input to a boolean value

order = order.lower() == "true"

# Check if the user wants to sort by rollno

if sort_key == "rollno":

    # Sort the dictionary by rollno using the sorted function and the keys method

    sorted_score = sorted(score.keys(), reverse=not order)

    # Print the header for the output

    print("\nRoll no\tMarks")

    # Loop through the sorted rollnos and print the corresponding marks

    for k in sorted_score:

        print(str(k) + '\t' + str(score[k]))

# Check if the user wants to sort by marks

elif sort_key == "marks":

    # Sort the dictionary by marks using the sorted function and the values method

    sorted_score = sorted(score.values(), reverse=not order)

    # Print the header for the output

    print("\nMarks\tRoll no")

    # Loop through the sorted marks and print the corresponding rollnos

    for k in sorted_score:

        # Find the rollno that has the same mark as k using the index method

        rollno = list(score.keys())[list(score.values()).index(k)]

        print(str(k) + '\t' + str(rollno))

# If the user enters an invalid sort key, print an error message

else:

    print("Invalid sort key. Please enter either rollno or marks.")

-endlock-

Remove Ads
Teachoo · Class 11 Explore Class 11
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh is an IIT Kanpur graduate and has been teaching for 16+ years. At Teachoo, he breaks down Maths, Science and Computer Science into simple steps so students understand concepts deeply and score with confidence.

Many students prefer Teachoo Black for a smooth, ad-free learning experience.