Skip to main content
 首页 » 编程设计

python之为什么当我不迭代时出现 "' NoneType' is not iterable"错误

2025年05月04日10kuangbin

运行以下脚本时

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 错误?

我确信这是一个明显的错误,但我看代码越多,看到它的机会就越少:)

请您参考如下方法:

您确实在迭代,因为这就是运算符in 的工作方式。当您这样做时: if 'Bond' not in d.get('b'): Python 将在左操作数 (d.得到('b'))。 d.get('b') == None 在第二个条目中因此异常。

您可以将第二个参数传递给 get这将被解释为在找不到元素以缓解此 if 子句的情况下获取的默认值:

if 'Bond' not in d.get('b',[]):