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
相关产品推荐
相关产品推荐

