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

Python如何按字典值的顺序获取对应键的有序列表

字典按值排序取键的实现方法

问题需求

现有Python字典:
d1= {570.44: 2, 305.21: 1, 271.94: 0, 463.20: 3, 556.60: 4, 596.27: 5}
需要得到字典的键组成的有序列表,排序规则为按照键对应的value值升序排列,而非按键本身的数值大小排序。预期输出结果为:
[271.94, 305.21, 570.44, 463.20, 556.60, 596.27]

实现代码

直接调用Python内置的sorted函数,指定key参数为字典的get方法即可:

d1 = {570.44: 2, 305.21: 1, 271.94: 0, 463.20: 3, 556.60: 4, 596.27: 5}
sorted_keys = sorted(d1, key=d1.get)
print(sorted_keys)

运行输出:
[271.94, 305.21, 570.44, 463.2, 556.6, 596.27]

原理解释

  • sorted函数遍历字典时,默认迭代对象是字典的所有键
  • key=d1.get表示排序时,取每个键在字典中对应的value作为排序的判断依据
  • 默认排序为升序,符合需求;如果需要按value降序排序,添加reverse=True参数即可:
    sorted_keys = sorted(d1, key=d1.get, reverse=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 15:27:02