Search code examples
pythonif-statementinputtypeskeyerror

got KeyError 1, have no idea what is wrong


I wrote a simple function to exercise set methodes. can somebody tell me why I got this error and how to solve it? thank you very much

n = int(input())
s = set(map(int, input().split()))
N=int(input())
for i in range(N):
    inputlist=input()
    if len(inputlist)==3:
        s.pop()
    else: 
        newl=inputlist.split()
        comand=newl[0]
        val=int(newl[1])
        
        if comand=='remove':
            s.remove(val)
        else:
            s.discard(val)
 --------------------------------------------------------------------------------------      
    "my input:"
    3
    1 2 3
    2
    pop
    remove 1

KeyError                                  Traceback (most recent call last)
<ipython-input-25-6ab5ebb8e508> in <module>
     11         val=int(newl[1])
     12         if comand=='remove':
---> 13             s.remove(val)
     14         else:
     15             s.discard(val)

KeyError: 1

Solution

  • you got an error because element{1} pop before, you can use try...except to not get error if element don't exist.

    try this:

    n = int(input())
    s = set(map(int, input().split()))
    N=int(input())
    for i in range(N):
        inputlist=input()
        if len(inputlist)==3:
            s.pop()
        else: 
            newl=inputlist.split()
            comand=newl[0]
            val=int(newl[1])        
            if comand=='remove':
                try:
                    s.remove(val)
                except:
                    print('val not exist')
            else:
                s.discard(val)