[英]KeyError using dictionary in Python
我正在嘗試編寫一個程序來查找特定金額的數字對。 它使用字典來存儲數字並相應地找到數字對。 代碼如下:
def printpairs(A, arr_size, sum):
hash = {}
for i in A:
hash[i] = None
for i in range(0,arr_size):
temp = sum - A[i]
if (temp >= 0 and hash[temp] == 1):
print sum, A[i], temp
hash[A[i]] = 1
A = [1,4,45,6,10,8]
printpairs(A, 6, 16)
我收到錯誤消息:
Keyerror : 15
我沒有弄錯我要去的地方。
一些說明可以幫助您理解問題:
hash
與A
大小相同,在您的示例中為6,其鍵為A
中的項 temp
為16 - A[0]
-> 16 - 1
> 15 hash[temp]
不存在,因為A
不包含15 請注意,您不需要傳遞列表的大小,可以使用len
將其包含在函數中。 同樣,在遇到此類問題時,請考慮使用調試器,它比Stack Overflow上的人員幫助您更快地找到問題。
Python會引發
KeyError
每當dict()
被請求的對象(使用格式a = adict[key]
)和鍵不在字典中。如果您不希望有異常,而是希望使用默認值,則可以使用
get()
方法:
A.get(15, 'default_value')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.