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

Python中如何正确排序含字母+数字键的字典?

解决带前缀字母的数字键字典排序问题

你的问题出在字符串排序逻辑和错误的键提取方式上:

  • Python默认对字符串按字符逐个比较,'e12'的第二个字符是'1',ASCII码比'e3'的'3'小,所以会排在前面——这是字符串排序的正常行为,但不符合你按数字大小排序的需求。
  • 你之前用lambda x: int(x[0])会直接报错,因为x[0]是完整的键(比如'e0'),包含字母'e',无法直接转成整数。

正确解法

核心是提取键里的数字部分,转成整数作为排序依据:

# 原字典
the_dict = {'e0': 50, 'e12': 89, 'e3': 110, 'e90': 18, 'e8': 82, 'e11': 40}

# 按键中的数字大小排序
sorted_items = sorted(the_dict.items(), key=lambda item: int(item[0][1:]))

# 转成有序字典(Python 3.7+ 原生字典支持插入顺序)
sorted_dict = dict(sorted_items)

print(sorted_dict)
# 输出:{'e0': 50, 'e3': 110, 'e8': 82, 'e11': 40, 'e12': 89, 'e90': 18}

代码解释

  • item[0]取到每个键(比如'e12')
  • item[0][1:]去掉前缀'e',得到纯数字字符串(比如'12')
  • int(...)把数字字符串转成整数,这样排序时就会按数字大小比较,而非字符串字符顺序。

如果你的键前缀不是固定的'e',而是任意字母/字符串,可以用正则提取数字部分,适配性更强:

import re

sorted_items = sorted(the_dict.items(), key=lambda item: int(re.search(r'\d+', item[0]).group()))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 06:44:55