简体   繁体   中英

Sorting values inside keys in dictionary

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!

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM