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

如何合并两个Python字典并将新出现的键对应值设置为0?

最优实现方案

Python中实现该需求最简洁高效的方式是使用字典推导式,单条表达式即可完成,无需引入任何第三方库。

核心逻辑

先取两个字典的键的并集,遍历所有键,用dict.get()方法取值,不存在的键默认返回0。

代码实现

Python 3.9+ 版本(推荐)

利用字典键视图的按位或运算符直接取并集,写法最简洁:

dict1 = {"I": 1, "like":1,"potatoes":1}
dict2 = {"I": 1, "like":1,"tomatoes":1}

# 单条表达式生成补全后的新字典
dict1_full = {k: dict1.get(k, 0) for k in dict1.keys() | dict2.keys()}
dict2_full = {k: dict2.get(k, 0) for k in dict1.keys() | dict2.keys()}

运行后输出完全符合需求:

dict1_full = {"I": 1, "like":1,"potatoes":1,"tomatoes":0}
dict2_full = {"I": 1, "like":1,"potatoes":0,"tomatoes":1}

兼容Python 3.8及更低版本

如果需要兼容旧版本Python,把并集写法替换为set的union方法即可:

all_keys = set(dict1).union(dict2)
dict1_full = {k: dict1.get(k, 0) for k in all_keys}
dict2_full = {k: dict2.get(k, 0) for k in all_keys}

原地修改原字典的方案

如果不需要保留原字典,想要直接修改原对象节省内存,也可以用update方法实现:

# 单条表达式原地补全dict1
dict1.update({k:0 for k in dict2 if k not in dict1})
# 单条表达式原地补全dict2
dict2.update({k:0 for k in dict1 if k not in dict2})

方案优势

  • 完全满足单条表达式的要求,写法简洁易读
  • 时间复杂度为O(m+n),m、n分别为两个字典的键数量,执行效率高
  • 不需要额外引入依赖,适配不同版本Python的需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 12:15:04