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

如何在Python中合并同结构的嵌套字典?

合并两个嵌套字典的Python实现方法

首先得提醒下:你原来的两个字典都用了appointment作为变量名,实际代码里得给它们起不同的名字,不然后定义的会直接覆盖前一个,比如改成appt_soccer和appt_gym,接下来分享几种简单好用的合并方法:

方法1:用字典解包(**运算符)生成新字典

这种方式会创建一个全新的合并字典,不会改动原来的两个字典,适合需要保留原数据的场景:

appt_soccer = { "soccer": { "day": 20, "month": "april" } }
appt_gym = { "gym": { "day": 5, "month": "may" } }

merged_appointment = {**appt_soccer, **appt_gym}
print(merged_appointment)
# 输出: {'soccer': {'day': 20, 'month': 'april'}, 'gym': {'day': 5, 'month': 'may'}}

方法2:用update()方法修改原有字典

如果不需要保留原始字典,可以直接把第二个字典的内容合并到第一个里面:

appt_soccer = { "soccer": { "day": 20, "month": "april" } }
appt_gym = { "gym": { "day": 5, "month": "may" } }

appt_soccer.update(appt_gym)
print(appt_soccer)
# 此时appt_soccer就是你要的合并结果

方法3:Python 3.9+ 专属的|运算符

Python 3.9及更高版本支持用|直接合并字典,语法更简洁直观:

appt_soccer = { "soccer": { "day": 20, "month": "april" } }
appt_gym = { "gym": { "day": 5, "month": "may" } }

merged_appointment = appt_soccer | appt_gym

小提示

因为你的两个字典顶层键(soccer和gym)是唯一的,所以以上方法都能完美生效。如果之后遇到顶层键重复的情况,后面的字典会覆盖前面字典中对应键的内容,这点要注意哦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:23:30