Python合并字典函数报错:'NoneType' object has no attribute 'keys'求解
合并字典时AttributeError错误的解决方法
错误根源
dict.update()返回None:你代码中d = d.update(dct)这行是核心问题。字典的update()方法是原地修改字典,不会返回新字典,而是返回None。第一次循环后d被赋值为None,下一次循环执行if k in d.keys()时,d是None,自然触发AttributeError。- 函数名不匹配:你定义的函数是
combine,但调用时用的是combine_dicts,这会导致NameError,必须修正函数名保持一致。 - 逻辑冗余且错误:你先遍历
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
相关产品推荐
相关产品推荐

