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

Python中如何对嵌套dict列表按多键分组并生成指定格式输出

解决方法

问题分析

你现有的代码逻辑是将字典的键值反转存储,把原始值作为新键、原始键作为值追加,完全不符合分组聚合的需求。要实现预期输出,只需要做三步操作:扁平化原始嵌套列表、格式化日期字段、按bot+date分组累加value即可,整体时间复杂度为O(n),效率很高。

完整实现代码

from collections import defaultdict

data = [
    [],
    [{'value': 8, 'bot': 'DB', 'month': 9, 'year': 2020}, {'value': 79, 'bot': 'DB', 'month': 10, 'year': 2020}, {'value': 126, 'bot': 'DB', 'month':8, 'year': 2021}],
    [],
    [{'value': 222, 'bot': 'GEMBOT', 'month': 11, 'year': 2020}, {'value': 623, 'bot': 'GEMBOT', 'month': 4, 'year': 2021}, {'value': 628, 'bot': 'GEMBOT', 'month': 9, 'year': 2021}],
    [{'value': 0, 'bot': 'GEMBOT', 'month': 4, 'year': 2021}],
    [{'value': 703, 'bot': 'DB', 'month': 11, 'year': 2020}, {'value': 1081, 'bot': 'DB', 'month': 3, 'year': 2021}, {'value': 1335, 'bot': 'DB', 'month': 10, 'year': 2020}, {'value': 1920, 'bot': 'DB', 'month': 4, 'year': 2021}, {'value': 2132, 'bot': 'DB', 'month': 1, 'year': 2021}, {'value': 2383, 'bot': 'DB', 'month': 2, 'year': 2021}]
]

# 自定义月份映射,9月用Sept符合你示例的格式
month_map = {
    1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun',
    7: 'Jul', 8: 'Aug', 9: 'Sept', 10: 'Oct', 11: 'Nov', 12: 'Dec'
}
# 分组累加容器,键是(bot, 日期)元组,值是对应value的总和
group_counter = defaultdict(int)

# 遍历扁平化所有条目
for sublist in data:
    # 跳过空列表
    if not sublist:
        continue
    for item in sublist:
        # 格式化日期为「月份缩写 年后两位」的格式
        date_str = f"{month_map[item['month']]} {str(item['year'])[-2:]}"
        group_key = (item['bot'], date_str)
        group_counter[group_key] += item['value']

# 转换为你需要的输出结构
result = [
    {"bot": key[0], "date": key[1], "value": val}
    for key, val in group_counter.items()
]

print(result)

输出结果

[
    {'bot': 'DB', 'date': 'Sept 20', 'value': 8},
    {'bot': 'DB', 'date': 'Oct 20', 'value': 1414},
    {'bot': 'DB', 'date': 'Aug 21', 'value': 126},
    {'bot': 'GEMBOT', 'date': 'Nov 20', 'value': 222},
    {'bot': 'GEMBOT', 'date': 'Apr 21', 'value': 623},
    {'bot': 'GEMBOT', 'date': 'Sept 21', 'value': 628},
    {'bot': 'DB', 'date': 'Nov 20', 'value': 703},
    {'bot': 'DB', 'date': 'Mar 21', 'value': 1081},
    {'bot': 'DB', 'date': 'Apr 21', 'value': 1920},
    {'bot': 'DB', 'date': 'Jan 21', 'value': 2132},
    {'bot': 'DB', 'date': 'Feb 21', 'value': 2383}
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 16:09:02