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

Python按年月字符串键排序字典 解决字符串排序顺序错乱问题

问题根因

当前排序使用的是默认的字符串字典序:字符逐位对比时,"2021-10"的第6位字符为1,小于"2021-2"的第6位字符2,因此2021-10会排在2021-2之前,不符合时间顺序要求。

解决方案

排序时不要直接用原始字符串做排序键,而是把年月字符串转换为整数类型的年月元组或者datetime对象,按时间维度排序即可。

方案1:手动拆分字符串转整数(轻量化实现)

不需要引入额外依赖,直接拆分年月转整数作为排序依据:

from collections import OrderedDict

raw_dict = {
    "2020-11": 25,
    "2020-12": 861,
    "2021-1": 935,
    "2021-10": 1,
    "2021-2": 4878,
    "2021-3": 6058,
    "2021-4": 3380,
    "2021-5": 4017,
    "2021-6": 1163,
    "2021-7": 620,
    "2021-8": 300,
    "2021-9": 7
}

# Python 3.7+ 普通字典默认保留插入顺序,可直接用dict
sorted_dict = dict(sorted(
    raw_dict.items(),
    key=lambda item: (int(item[0].split("-")[0]), int(item[0].split("-")[1]))
))

# 需兼容3.7以下版本的话,改用OrderedDict
# sorted_dict = OrderedDict(sorted(
#     raw_dict.items(),
#     key=lambda item: (int(item[0].split("-")[0]), int(item[0].split("-")[1]))
# ))

方案2:借助datetime模块转换(扩展性更强)

如果后续时间格式可能扩展到日、时分秒,用datetime转换更通用,不容易出错:

from datetime import datetime
from collections import OrderedDict

raw_dict = {
    "2020-11": 25,
    "2020-12": 861,
    "2021-1": 935,
    "2021-10": 1,
    "2021-2": 4878,
    "2021-3": 6058,
    "2021-4": 3380,
    "2021-5": 4017,
    "2021-6": 1163,
    "2021-7": 620,
    "2021-8": 300,
    "2021-9": 7
}

sorted_dict = dict(sorted(
    raw_dict.items(),
    key=lambda item: datetime.strptime(item[0], "%Y-%m")
))

两种方案输出的结果都和预期的时间顺序完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 10:24:02