简体   繁体   中英

KeyError using dictionary in Python

I am trying to write a program to find pair of numbers for a particular sum. It uses a dictionary to store the numbers and find the pair accordingly. The code is as follows:

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)

I am getting error :

Keyerror : 15

I am not getting where I am going wrong.

Few notes that will help you understanding your problem:

  • hash has the same size as A , in your example, it's 6 and its keys are the items in A
  • In the first iteration, temp is 16 - A[0] -> 16 - 1 -> 15
  • hash[temp] doesn't exist since A doesn't contain 15

Please note that you don't need to pass the list's size, you can have it within the function by using len . Also when having this kind of problems, consider using the debugger, it'll help you find your problem faster than people on Stack Overflow.

Python raises a KeyError whenever a dict() object is requested (using the format a = adict[key] ) and the key is not in the dictionary.

If you don't want to have an exception but would rather a default value used instead, you can use the get() method:

A.get(15, 'default_value')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM