[英]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 :您可以使用字典理解和带有key参数的
sorted
函数:
{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).这将创建具有相同的键作为一个新的字典
students
,但与每个值以相反的顺序排序在它的第二个元素(得分)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.