python - 我在 python 中遇到关键错误

在我的 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/

相关文章:

python - 在 python shell 中按箭头键时看到转义字符

linux - 使用 awk 保存修改

linux - 重命名文件和目录(添加前缀)

python - python,del或delattr哪个更好?

python - 在python中通过分隔符拆分字符串

c - C 到毫秒是否有替代 sleep 功能?

linux - 如何来回反向搜索?

linux - 查找和复制文件

linux - 什么进程正在使用我所有的磁盘 IO

python - BeautifulSoup 获取 href