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

Python字典合并求助:将多字典列表转换为单字典(值为列表)

字典列表转聚合字典的解决方法

嘿,这问题挺常见的,我给你几个实用的解法,你可以根据自己的习惯和场景选择:

方法一:基础循环遍历(新手友好)

这个方法逻辑直白,一步步处理每个字典,非常容易理解:

data = [{'x': 3, 'y': 3}, {'x': 5, 'y': 3}, {'x': 1, 'y': 4}]
result = {'x': [], 'y': []}

for item in data:
    result['x'].append(item['x'])
    result['y'].append(item['y'])

print(result)  # 输出: {'x': [3, 5, 1], 'y': [3, 3, 4]}

如果你的字典里的键不确定,或者未来可能新增其他键,可以改成动态初始化的版本,兼容性更强:

data = [{'x': 3, 'y': 3}, {'x': 5, 'y': 3}, {'x': 1, 'y': 4}]
result = {}

for item in data:
    for key, value in item.items():
        if key not in result:
            result[key] = []
        result[key].append(value)

print(result)  # 同样得到目标结果

方法二:字典推导式 + 列表推导(简洁高效)

如果你喜欢紧凑的代码,这个写法会很顺手:

data = [{'x': 3, 'y': 3}, {'x': 5, 'y': 3}, {'x': 1, 'y': 4}]
result = {key: [d[key] for d in data] for key in data[0].keys()}

print(result)

这里先提取第一个字典的所有键,再通过列表推导遍历每个字典,收集对应键的值组成列表。

方法三:使用collections.defaultdict(复杂场景适配)

如果需要处理键可能缺失的复杂场景,defaultdict能帮你省去手动判断键是否存在的步骤:

from collections import defaultdict

data = [{'x': 3, 'y': 3}, {'x': 5, 'y': 3}, {'x': 1, 'y': 4}]
result = defaultdict(list)

for item in data:
    for key, value in item.items():
        result[key].append(value)

# 若需要转换成普通字典,直接用dict(result)即可
print(dict(result))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:31:42