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

Python如何将日期类嵌套列表转换为指定结构的嵌套字典

嵌套日期列表转嵌套字典实现方案

核心思路

  • 逐层处理日期的三级结构:年 → 月 → 日,依次为每一层级初始化对应的容器(字典存年月映射,列表存当月日期)
  • 遍历所有输入的日期子项,将日数据追加到对应年月的列表中即可

代码实现

方法1:使用基础字典实现(无需导入第三方模块)

def convert_date_list(input_list):
    result = {}
    for day, month, year in input_list:
        # 初始化年份层级
        if year not in result:
            result[year] = {}
        # 初始化月份层级
        if month not in result[year]:
            result[year][month] = []
        # 追加日期
        result[year][month].append(day)
    return result

方法2:使用collections.defaultdict简化判断逻辑

from collections import defaultdict

def convert_date_list(input_list):
    # 嵌套defaultdict结构:最外层是字典,值是字典,内层字典的值是列表
    result = defaultdict(lambda: defaultdict(list))
    for day, month, year in input_list:
        result[year][month].append(day)
    # 如果需要输出原生字典结构,可放开下行注释做转换
    # return {k: dict(v) for k, v in result.items()}
    return result

效果验证

输入测试数据:

test_input = [
    [11, 'January', 2021],
    [12, 'January', 2021],
    [13, 'January', 2021],
    [1, 'February', 2021],
    [13, 'June', 2022],
    [14, 'June', 2022],
    [15, 'June', 2022]
]
print(convert_date_list(test_input))

输出结果完全匹配目标结构要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 18:48:04