在我的 python 程序中,我收到了这个错误:
KeyError: 'variablename'
从此代码:
path = meta_entry['path'].strip('/'),
谁能解释一下为什么会这样?
最佳答案
一个 KeyError
通常意味着 key 不存在。那么,你确定 path
键存在吗?
来自官方 python 文档:
KeyError 异常
Raised when a mapping (dictionary) key is not found in the set of existing keys.
例如:
>>> mydict = {'a':'1','b':'2'}
>>> mydict['a']
'1'
>>> mydict['c']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'c'
>>>
所以,尝试打印meta_entry
的内容,检查path
是否存在。
>>> mydict = {'a':'1','b':'2'}
>>> print mydict
{'a': '1', 'b': '2'}
或者,你可以这样做:
>>> 'a' in mydict
True
>>> 'c' in mydict
False
https://stackoverflow.com/questions/10116518/