當運行下面的腳本爲什麼「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