【问题标题】:How can I sort a key within the dictionaries into descending order? [duplicate]如何将字典中的键按降序排序? [复制]
【发布时间】:2015-12-28 17:04:09
【问题描述】:

我对 python 很陌生,我想将所有最高分数按降序排序。 (有一个字典存储每个学生的数据)目前它只按照输入数据的顺序打印每个学生的最高分数:

Maximum score
Adam Watts 7
Henry Lloyd 10
Lucy Smith 9   

这是我正在使用的代码:

print("Maximum score")
for key in keys:
    print(key, max(Classes[key]))

【问题讨论】:

  • 你的字典到底长什么样?你期待什么结果?只是打印?请编辑您的帖子,使其有意义。
  • 你的字典的结构是什么?

标签: python sorting dictionary


【解决方案1】:

假设你的字典是这样的:

students = {'Adam Watts': [3, 7], 'Henry Lloyd': [10, 1], 'Lucy Smith': [9, 9]}

您不能对字典进行排序(字典中的条目没有特定的顺序),但是您可以将您关心的数据存储在一个列表中,并对这个列表进行排序。

from operator import itemgetter
items = [(student, max(scores)) for student, scores in students.items()]
items.sort(key=itemgetter(1), reverse=True)

for student, score in items:
    print(student, score)

【讨论】:

    猜你喜欢
    • 2016-11-22
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    • 1970-01-01
    • 2017-08-06
    • 2021-12-20
    • 2021-06-28
    相关资源
    最近更新 更多