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

如何按值列表的首个元素对Python字典进行排序?

按值列表首元素排序Python字典的实现方法

完全可行,具体实现分两种场景:

1. Python 3.7+(原生字典支持有序)

直接用sorted()函数结合字典的items()方法,指定排序依据为值列表的第一个元素即可:

dct = {'a' : [1,2] , 'b' : [5,9] , 'c' : [3,8] , 'd' : [0,1]}
# 按值列表的第一个元素升序排序
sorted_dct = dict(sorted(dct.items(), key=lambda x: x[1][0]))
print(sorted_dct)
# 输出: {'d': [0, 1], 'a': [1, 2], 'c': [3, 8], 'b': [5, 9]}
  • 说明:sorted(dct.items(), key=lambda x: x[1][0])会把字典的键值对元组按值列表的第一个元素排序,最后通过dict()转换为有序字典。

2. Python 3.6及以下(原生字典无序)

需要借助collections.OrderedDict来保存排序后的有序结构:

from collections import OrderedDict
dct = {'a' : [1,2] , 'b' : [5,9] , 'c' : [3,8] , 'd' : [0,1]}
sorted_dct = OrderedDict(sorted(dct.items(), key=lambda x: x[1][0]))
print(sorted_dct)
# 输出: OrderedDict([('d', [0, 1]), ('a', [1, 2]), ('c', [3, 8]), ('b', [5, 9])])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 19:33:23