[英]AttributeError: 'NoneType' object has no attribute 'keys' (Python)
I'm writing a function that takes a number of dictionaries (keys - letters, values - numbers) and combines them into one dictionary.我正在写一个 function,它需要一些字典(键 - 字母,值 - 数字)并将它们组合成一个字典。 Dict values should be summarized in case of identical keys, but alwayw recieve the error for the line with " if k in d.keys():" AttributeError: 'NoneType' object has no attribute 'keys'
在相同键的情况下应该总结字典值,但总是收到错误“if k in d.keys():” AttributeError: 'NoneType' object has no attribute '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)
result should be {'a': 600, 'b': 200, 'c': 300, 'd': 100}结果应该是 {'a': 600, 'b': 200, 'c': 300, 'd': 100}
I found the answer) since dictionaries are mutable are should've used d.update() instead of d = d.update().我找到了答案)因为字典是可变的,所以应该使用 d.update() 而不是 d = d.update()。 And one else mistake, but not according to the question topic
还有一个错误,但不是根据问题主题
It looks like you want to accumulate values from the other two dicts into the first one, or just transfer values if not already present.看起来您想将其他两个字典中的值累积到第一个字典中,或者如果不存在则只是转移值。
This is the code you want:这是你想要的代码:
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)
Output as requested Output 按要求
What's wrong with your code.你的代码有什么问题。
1. d = d.update(dct)
will override exist data and and that's where you are getting AttributeError:
because a none is returned. 1.
d = d.update(dct)
将覆盖现有数据,这就是您获得AttributeError:
的地方,因为没有返回。 2. You are calling a wrong function, your function is called combine
and you are calling combine_dicts
. 2. 你打错了 function,你的 function 叫
combine
而你叫的是combine_dicts
。
This is one of the appropriate approaches you can take you can taking using defaultdict
from collections.这是您可以采用的适当方法之一,您可以使用 collections 中的
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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.