我在 python 中遇到关键错误 [英] I'm getting Key error in python

查看:27
本文介绍了我在 python 中遇到关键错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 python 程序中,我收到此错误:

KeyError: '变量名'

来自此代码:

path = meta_entry['path'].strip('/'),

谁能解释一下为什么会这样?

解决方案

A KeyError 通常表示密钥不存在.那么,您确定 path 键存在吗?

来自官方python文档:

异常KeyError

<块引用>

在集合中未找到映射(字典)键时引发现有密钥.

例如:

<预><代码>>>>mydict = {'a':'1','b':'2'}>>>mydict['a']'1'>>>mydict['c']回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中密钥错误:'c'>>>

因此,尝试打印meta_entry的内容并检查path是否存在.

<预><代码>>>>mydict = {'a':'1','b':'2'}>>>打印 mydict{'a':'1','b':'2'}

或者,您可以这样做:

<预><代码>>>>'a' 在 mydict真的>>>'c' 在 mydict错误的

In my python program I am getting this error:

KeyError: 'variablename'

From this code:

path = meta_entry['path'].strip('/'),

Can anyone please explain why this is happening?

解决方案

A KeyError generally means the key doesn't exist. So, are you sure the path key exists?

From the official python docs:

exception KeyError

Raised when a mapping (dictionary) key is not found in the set of existing keys.

For example:

>>> mydict = {'a':'1','b':'2'}
>>> mydict['a']
'1'
>>> mydict['c']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'c'
>>>

So, try to print the content of meta_entry and check whether path exists or not.

>>> mydict = {'a':'1','b':'2'}
>>> print mydict
{'a': '1', 'b': '2'}

Or, you can do:

>>> 'a' in mydict
True
>>> 'c' in mydict
False

这篇关于我在 python 中遇到关键错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆