当运行下面的脚本为什么“NoneType”不可迭代“错误,当我不迭代?
dictlist = [
{'a': 'hello world', 'b': 'my name is Bond'},
{'a': 'bonjour monde'}
]
for d in dictlist:
if 'Bond' not in d.get('b'):
print d
我预期的输出是空的(第一字典确实不匹配,第二个是缺少关键'b'
),但我得到的错误:
Traceback (most recent call last):
File "C:/dev/mytest.py", line 7, in <module>
if 'Bond' not in d.get('b'):
TypeError: argument of type 'NoneType' is not iterable
我很困惑:为什么有一个argument of type 'NoneType' is not iterable
错误,而我不迭代(至少在该行)?
我相信这是一个明显的错误,但我越是看代码的机会少,我看到它:)
谢谢。所有响应都很好 - 感谢额外的位(默认值不会有帮助,因为它会匹配'if') – WoJ
@WoJ不,只有默认值不匹配。请让我知道,如果你有不同的理解。 – thefourtheye
如果我在d.get('b',“”)中不使用'if'Bond',那么当'b'不存在时,将返回一个空字符串,它将匹配'if'Bond'不在' - 这不是我想要的(''b''根本不存在,所以测试(从逻辑角度来看)是无效的)。 **你的代码是好的**:i)''b''必须存在以便ii)它被检查为'Bond' – WoJ