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

如何将多个字典组成的列表合并为一个完整字典?

将字典列表合并为单个字典

这里有几种实用的Python方法可以实现你的需求:

方法1:字典推导式

这是最简洁的写法之一,通过嵌套遍历收集所有键值对:

input_list = [
    {'fruit': 'banana', 'color1': ''},
    {'vegetable': 'tomato', 'color2': ''},
    {'dessert': 'ice cream', 'taste': ''}
]

desired_output = {k: v for d in input_list for k, v in d.items()}
print(desired_output)

方法2:使用update()方法

通过初始化空字典,逐个合并列表中的字典:

input_list = [
    {'fruit': 'banana', 'color1': ''},
    {'vegetable': 'tomato', 'color2': ''},
    {'dessert': 'ice cream', 'taste': ''}
]

desired_output = {}
for d in input_list:
    desired_output.update(d)
print(desired_output)

方法3:Python 3.9+ 专属的字典合并运算符|

如果你的Python版本在3.9及以上,可以用更直观的合并运算符:

循环合并

input_list = [
    {'fruit': 'banana', 'color1': ''},
    {'vegetable': 'tomato', 'color2': ''},
    {'dessert': 'ice cream', 'taste': ''}
]

desired_output = {}
for d in input_list:
    desired_output |= d
print(desired_output)

结合functools.reduce一行完成

from functools import reduce

input_list = [
    {'fruit': 'banana', 'color1': ''},
    {'vegetable': 'tomato', 'color2': ''},
    {'dessert': 'ice cream', 'taste': ''}
]

desired_output = reduce(lambda a, b: a | b, input_list, {})
print(desired_output)

注意:如果列表中的字典存在重复键,后面的字典键值会覆盖前面的,比如两个字典都有'fruit'键,最终结果会保留最后一个字典里的'fruit'值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 05:10:33