属性错误:'NoneType'对象没有属性'keys' (Python)



我正在编写一个函数,它接受许多字典(键-字母,值-数字)并将它们组合成一个字典。在键相同的情况下,应该总结字典值,但总是收到带有"的行错误。如果k in d.keys():"AttributeError: 'NoneType'对象没有属性'keys'

def combine(*args):
d = args[0]
for dct in args[1:]:
for k, v in dct.items():
if k in d.keys():
d[k] = d[k] + v
d = d.update(dct)
print(d)

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

结果应该{' a ': 600, ' b ': 200, ' c ': 300, ' d ': 100}

你的代码有什么问题?
1。d = d.update(dct)将覆盖存在的数据,这就是你得到AttributeError:的地方,因为返回一个none。2. 您调用了一个错误的函数,您的函数是combine,而您正在调用combine_dicts

这是你可以采取的一种适当的方法,你可以使用defaultdict从集合。

from collections import defaultdict
def combine(*args):
d = defaultdict(int)
for dct in args:
for key, value in dct.items():
d[key] += value
print(dict(d))
dict_1 = {'a': 100, 'b': 200}
dict_2 = {'a': 200, 'c': 300}
dict_3 = {'a': 300, 'd': 100}
combine(dict_1, dict_2, dict_3)

{'a': 600, 'b': 200, 'c': 300, 'd': 100}

我找到答案了)因为字典是可变的,所以应该使用d.update()而不是d = d.update()。还有一个错误,但不是根据问题主题

看起来您想要将其他两个字典中的值累积到第一个字典中,或者只是传输尚未存在的值。

这是你想要的代码:

def combine(*args):
d = args[0]
for dct in args[1:]:
for k, v in dct.items():
if k in d.keys():
d[k] = d[k] + v
else:
d[k] = v

print(d)

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

按要求输出

最新更新