Home > Mobile >  Sorting values inside keys in dictionary
Sorting values inside keys in dictionary

Time:11-10

Hello i have a dictionary

students = {"john": [["math", 84], ["science", 70], ["programing", 95]],
            "veronica": [["math", 90], ["science", 76 ], ["programing", 80]]}

i would like to sort this dictionary by points they achivied from classes so it would like this

students = {"john": [["programing", 95],["math", 84], ["science", 70]],
            "veronica": [["math", 90], ["programing", 80], ["science", 76 ]]}

but i have no idea how to do that, i would really apreciate help. Thanks!

CodePudding user response:

You can use a dictionary comprehension and the sorted function with the key parameter:

{k: sorted(v, key=lambda x: x[1], reverse=True) for k, v in students.items()}

This will create a new dictionary with the same keys as students, but with each value sorted in reverse order by the second element in it (the score).

  • Related