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

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

问题描述

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

In my python program I am getting this error:

KeyError: 'variablename'

从此代码:

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

任何人都可以解释为什么正在发生?

Can anyone please explain why this is happening?

推荐答案

A KeyError 通常意味着密钥不存在。所以,你确定路径密钥存在吗?

从官方的python文档:

From the official python docs:

异常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的内容并检查路径是否存在。

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'}

或者你可以做:

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

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

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