问题:我在python中遇到关键错误

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

KeyError: 'variablename'

从此代码:

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

谁能解释为什么会这样?

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?


回答 0

一个通常意味着该键不存在。那么,您确定path密钥存在吗?

来自官方python文档:

异常KeyError

在现有键集中找不到映射(字典)键时引发。

例如:

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

A 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

回答 1

我完全同意主要错误评论。您也可以使用字典的get()方法来避免出现异常。这也可以用来提供默认路径,而不是None如下所示。

>>> d = {"a":1, "b":2}
>>> x = d.get("A",None)
>>> print x
None

I fully agree with the Key error comments. You could also use the dictionary’s get() method as well to avoid the exceptions. This could also be used to give a default path rather than None as shown below.

>>> d = {"a":1, "b":2}
>>> x = d.get("A",None)
>>> print x
None

回答 2

对于字典,只需使用

if key in dict

而不使用

if key in dict.keys()

会很费时间

For dict, just use

if key in dict

and don’t use searching in key list

if key in dict.keys()

The latter will be more time-consuming.


回答 3

是的,它很可能是由不存在的密钥引起的。

在我的程序中,出于效率考虑,我使用setdefault将此错误静音。取决于这条线的效率

>>>'a' in mydict.keys()  

我也是Python的新手。实际上,我今天才学到它。因此,请原谅我对效率的无知。

在Python 3中,您也可以使用此功能,

get(key[, default]) [function doc][1]

据说它永远不会引发关键错误。

Yes, it is most likely caused by non-exsistent key.

In my program, I used setdefault to mute this error, for efficiency concern. depending on how efficient is this line

>>>'a' in mydict.keys()  

I am new to Python too. In fact I have just learned it today. So forgive me on the ignorance of efficiency.

In Python 3, you can also use this function,

get(key[, default]) [function doc][1]

It is said that it will never raise a key error.


回答 4

这意味着您的阵列缺少要查找的键。我用一个函数处理此问题,该函数要么返回值(如果存在),要么返回默认值。

def keyCheck(key, arr, default):
    if key in arr.keys():
        return arr[key]
    else:
        return default


myarray = {'key1':1, 'key2':2}

print keyCheck('key1', myarray, '#default')
print keyCheck('key2', myarray, '#default')
print keyCheck('key3', myarray, '#default')

输出:

1
2
#default

This means your array is missing the key you’re looking for. I handle this with a function which either returns the value if it exists or it returns a default value instead.

def keyCheck(key, arr, default):
    if key in arr.keys():
        return arr[key]
    else:
        return default


myarray = {'key1':1, 'key2':2}

print keyCheck('key1', myarray, '#default')
print keyCheck('key2', myarray, '#default')
print keyCheck('key3', myarray, '#default')

Output:

1
2
#default

回答 5

我在dict使用nested 进行解析时收到此错误for

cats = {'Tom': {'color': 'white', 'weight': 8}, 'Klakier': {'color': 'black', 'weight': 10}}
cat_attr = {}
for cat in cats:
    for attr in cat:
        print(cats[cat][attr])

追溯:

Traceback (most recent call last):
      File "<input>", line 3, in <module>
    KeyError: 'K'

因为在第二个循环中应该cats[cat]只是cat(只是一个键)

所以:

cats = {'Tom': {'color': 'white', 'weight': 8}, 'Klakier': {'color': 'black', 'weight': 10}}
cat_attr = {}
for cat in cats:
    for attr in cats[cat]:
        print(cats[cat][attr])

black
10
white
8

I received this error when I was parsing dict with nested for:

cats = {'Tom': {'color': 'white', 'weight': 8}, 'Klakier': {'color': 'black', 'weight': 10}}
cat_attr = {}
for cat in cats:
    for attr in cat:
        print(cats[cat][attr])

Traceback:

Traceback (most recent call last):
      File "<input>", line 3, in <module>
    KeyError: 'K'

Because in second loop should be cats[cat] instead just cat (what is just a key)

So:

cats = {'Tom': {'color': 'white', 'weight': 8}, 'Klakier': {'color': 'black', 'weight': 10}}
cat_attr = {}
for cat in cats:
    for attr in cats[cat]:
        print(cats[cat][attr])

Gives

black
10
white
8

回答 6

例如,如果这是一个数字:

ouloulou={
    1:US,
    2:BR,
    3:FR
    }
ouloulou[1]()

它工作正常,但是 如果使用例如:

ouloulou[input("select 1 2 or 3"]()

它不起作用,因为您的输入返回字符串’1’。所以你需要使用int()

ouloulou[int(input("select 1 2 or 3"))]()

For example, if this is a number :

ouloulou={
    1:US,
    2:BR,
    3:FR
    }
ouloulou[1]()

It’s work perfectly, but if you use for example :

ouloulou[input("select 1 2 or 3"]()

it’s doesn’t work, because your input return string ‘1’. So you need to use int()

ouloulou[int(input("select 1 2 or 3"))]()

回答 7

让我们简化一下,如果您使用的是Python 3

mydict = {'a':'apple','b':'boy','c':'cat'}
check = 'c' in mydict
if check:
    print('c key is present')

如果您需要其他条件

mydict = {'a':'apple','b':'boy','c':'cat'}
if 'c' in mydict:
    print('key present')
else:
    print('key not found')

对于动态键值,还可以通过try-exception块进行处理

mydict = {'a':'apple','b':'boy','c':'cat'}
try:
    print(mydict['c'])
except KeyError:
    print('key value not found')mydict = {'a':'apple','b':'boy','c':'cat'}

Let us make it simple if you’re using Python 3

mydict = {'a':'apple','b':'boy','c':'cat'}
check = 'c' in mydict
if check:
    print('c key is present')

If you need else condition

mydict = {'a':'apple','b':'boy','c':'cat'}
if 'c' in mydict:
    print('key present')
else:
    print('key not found')

For the dynamic key value, you can also handle through try-exception block

mydict = {'a':'apple','b':'boy','c':'cat'}
try:
    print(mydict['c'])
except KeyError:
    print('key value not found')mydict = {'a':'apple','b':'boy','c':'cat'}

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。