You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 中如何对 dictionary(字典)内的元素进行排序

Python字典按分数排序取TOP5实现方法

你现有代码只需要补充排序+截取前5的逻辑即可,另外注意你当前函数有个小问题:定义时接收了students、marks两个参数,但生成字典时直接用了全局的Students、Marks变量,参数没有实际生效,修正后的完整代码如下:

Students=['student1','student2','student3','student4','student5','student6','student7','student8','student9','student10']
Marks = [45, 78, 12, 14, 48, 43, 47, 98, 35, 80]

def display_dash_board(students, marks):
    # 改用函数传入的参数生成字典,避免依赖全局变量
    dictionary = dict(zip(students, marks))
    print(type(dictionary))

    print('top_5_students')
    # 核心逻辑:按分数倒序排序,取前5个
    sorted_stu = sorted(dictionary.items(), key=lambda x: x[1], reverse=True)
    top5 = sorted_stu[:5]
    
    for key, value in top5:
        print((key, value))

# 调用函数验证
display_dash_board(Students, Marks)

关键逻辑说明

  • sorted()方法的key参数指定排序规则:lambda x: x[1]表示按键值对的第二个元素(也就是分数)排序
  • reverse=True设置为降序排列,保证分数最高的排在最前面
  • 排序后的结果是列表结构,直接用[:5]切片即可截取前5个元素
  • 如果需要处理同分场景,比如同分的学生按名字正序排列,可以把排序规则修改为key=lambda x: (-x[1], x[0]),先按分数倒序,再按名字字典序升序

内容的提问来源于stack exchange,提问作者Atif Hossain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 06:45:03