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

Python中如何对嵌套字典的值按列表索引6位元素进行升序/降序排序

Python字典按值列表指定索引排序实现方法

原数据结构

original_dict = {
    0: ['70', '70', '70', 'A12345678', 'JONE', 'BIT', 70, 'C'],
    1: ['80', '80', '80', 'A12334567', 'ERIC', 'DIT', 80, 'CP'],
    2: ['55', '60', '70', 'A12345679', 'HARRY', 'BIT', 63, 'P'],
    3: ['45', '45', '45', 'A11223344', 'NEW', 'BIT', 45, 'F']
}

实现逻辑

Python的sorted()函数支持通过key参数指定排序依据,对于字典结构,我们先通过items()方法获取所有(键, 值)对,再指定排序key为值列表索引为6的元素即可。

注意:Python 3.7及以上版本原生支持字典保留插入顺序,低版本Python需要使用collections.OrderedDict存储排序后的结果。

具体代码实现

1. 升序排序(从小到大)

# Python 3.7+ 直接生成有序字典
asc_sorted_dict = dict(sorted(original_dict.items(), key=lambda item: item[1][6]))

# 兼容低版本Python 使用OrderedDict
from collections import OrderedDict
asc_sorted_ordered = OrderedDict(sorted(original_dict.items(), key=lambda item: item[1][6]))

升序排序后输出结果:

{
    3: ['45', '45', '45', 'A11223344', 'NEW', 'BIT', 45, 'F'],
    2: ['55', '60', '70', 'A12345679', 'HARRY', 'BIT', 63, 'P'],
    0: ['70', '70', '70', 'A12345678', 'JONE', 'BIT', 70, 'C'],
    1: ['80', '80', '80', 'A12334567', 'ERIC', 'DIT', 80, 'CP']
}

2. 降序排序(从大到小)

添加reverse=True参数即可实现降序:

# Python 3.7+
desc_sorted_dict = dict(sorted(original_dict.items(), key=lambda item: item[1][6], reverse=True))

# 兼容低版本Python
from collections import OrderedDict
desc_sorted_ordered = OrderedDict(sorted(original_dict.items(), key=lambda item: item[1][6], reverse=True))

降序排序后输出结果:

{
    1: ['80', '80', '80', 'A12334567', 'ERIC', 'DIT', 80, 'CP'],
    0: ['70', '70', '70', 'A12345678', 'JONE', 'BIT', 70, 'C'],
    2: ['55', '60', '70', 'A12345679', 'HARRY', 'BIT', 63, 'P'],
    3: ['45', '45', '45', 'A11223344', 'NEW', 'BIT', 45, 'F']
}

额外说明

  • 若不需要保留字典结构,可直接获取排序后的键值对列表使用:sorted_items = sorted(original_dict.items(), key=lambda x: x[1][6])
  • 如果你场景中索引6的元素是字符串格式的数字,需要额外做类型转换:key=lambda item: int(item[1][6])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:15:03