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

如何将Python中多个独立字典合并为单个字典

嘿,先纠正个小细节:你写的x = {'col1': 1} {'col2': 10}在Python里是语法错误,没法直接这么定义变量哦。得把这些独立字典放到一个容器(比如列表、元组)里,比如dicts = [{'col1': 1}, {'col2': 10}],这样才能进行合并操作~

下面给你几种实用的合并方法:

1. 字典解包(Python 3.5+ 最简洁)

如果是固定数量的字典,直接用**解包到新字典里:

dict1 = {'col1': 1}
dict2 = {'col2': 10}
merged_dict = {**dict1, **dict2}
print(merged_dict)  # 输出: {'col1': 1, 'col2': 10}

如果是不确定数量的字典(存在列表/元组里),可以配合循环更新:

dicts = [{'col1': 1}, {'col2': 10}]
merged_dict = {}
for d in dicts:
    merged_dict.update(d)

2. 使用|运算符(Python 3.9+ 更直观)

Python 3.9引入了字典合并运算符|,用起来非常清爽:

dict1 = {'col1': 1}
dict2 = {'col2': 10}
merged_dict = dict1 | dict2
# 要是想直接更新其中一个字典,用 |=
dict1 |= dict2
print(dict1)  # 输出: {'col1': 1, 'col2': 10}

3. 传统循环+update(兼容所有Python版本)

如果需要兼容老版本Python,最稳妥的就是用update()方法循环合并:

dicts = [{'col1': 1}, {'col2': 10}]
merged_dict = {}
for d in dicts:
    merged_dict.update(d)
print(merged_dict)

⚠️ 注意:如果多个字典里有重复的键,后面的字典会覆盖前面的键值,比如[{'col1':1}, {'col1':2}]合并后,col1的值会是2。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:50:47