簡體   English   中英

我在 python 中遇到關鍵錯誤

[英]I'm getting Key error in python

在我的 python 程序中,我收到此錯誤:

KeyError: 'variablename'

從這段代碼:

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

誰能解釋為什么會這樣?

KeyError通常意味着密鑰不存在。 那么,您確定path鍵存在嗎?

來自官方 python 文檔:

異常鍵錯誤

當在現有鍵集中找不到映射(字典)鍵時引發。

例如:

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

我完全同意關鍵錯誤評論。 您也可以使用字典的 get()方法來避免異常。 這也可以用於提供默認路徑而不是None ,如下所示。

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

對於dict,只需使用

if key in dict

並且不要在密鑰列表中使用搜索

if key in dict.keys()

后者會更耗時。

是的,這很可能是由不存在的密鑰引起的。

在我的程序中,出於效率考慮,我使用 setdefault 來消除此錯誤。 取決於這條線的效率如何

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

我也是 Python 新手。 其實我今天才學的。 所以請原諒我對效率的無知。

在 Python 3 中,你也可以使用這個函數,

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

據說它永遠不會引發關鍵錯誤。

當我使用嵌套for解析dict時收到此錯誤:

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

如果您使用的是 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'}

這意味着您的陣列缺少您要查找的密鑰。 我使用一個函數來處理這個問題,該函數要么返回值(如果存在),要么返回默認值。

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

例如,如果這是一個數字:

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"))]()

我建議重置 Pandas 數據框的索引:

df.reset_index(drop=True, inplace=True)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM