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

Python合并字典函数报错:'NoneType' object has no attribute 'keys'求解

合并字典时AttributeError错误的解决方法

错误根源

  1. dict.update()返回None:你代码中d = d.update(dct)这行是核心问题。字典的update()方法是原地修改字典,不会返回新字典,而是返回None。第一次循环后d被赋值为None,下一次循环执行if k in d.keys()时,d是None,自然触发AttributeError。
  2. 函数名不匹配:你定义的函数是combine,但调用时用的是combine_dicts,这会导致NameError,必须修正函数名保持一致。
  3. 逻辑冗余且错误:你先遍历dct累加相同键的值,随后又调用update(dct),这会把已经累加好的键值覆盖回dct中的原值,完全违背了“求和”的需求。

修正后的代码

下面是实现需求的正确写法,同时避免修改原输入字典:

def combine_dicts(*args):
    combined = {}
    for dct in args:
        for key, value in dct.items():
            # 用get方法处理不存在的键,默认值为0,直接累加
            combined[key] = combined.get(key, 0) + value
    return combined

dict_1 = {'a': 100, 'b': 200}
dict_2 = {'a': 200, 'c': 300}
dict_3 = {'a': 300, 'd': 100}

result = combine_dicts(dict_1, dict_2, dict_3)
print(result)  # 输出: {'a': 600, 'b': 200, 'c': 300, 'd': 100}

另一种简化写法(Python 3.9+)

如果你使用Python 3.9及以上版本,可以用字典合并运算符|配合functools.reduce实现更简洁的代码:

from functools import reduce

def combine_dicts(*args):
    return reduce(lambda a, b: {k: a.get(k, 0) + b.get(k, 0) for k in a | b}, args)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 00:16:08