Search code examples
pythonsetkeyerror

Getting KeyError when removing element in set even though element is in set?


Hello I've started using python fairly recently. I'm having so much trouble with this one segment of my code that gives me a keyerror when I try to remove an element from my set:

tiles.remove(m) KeyError: 'B9'

EDIT: I forgot to mention that the m value changes everytime I call another function before the for loop. Also in the fc function, if it is false the function makes sure to add the tile back into the set tiles.add(m)

Researching online it says a keyerror only occurs when the element is not in the set but....right before I remove the element, I check to see that it is in the set and it is.

m = findMRV() 

if checkEmpty(board, m) == False:
    backtrack(board)     

for d in domain[m].copy():
    if checkValid(board, m[0], m[1], d ): 
        if m in tiles:
            print(str(m)+"HELLO3")
        tiles.remove(m) 
        board[m] = d

    if(fc(board, m[0], m1], d) == False):
        continue

the checkValid function just returns true or false and doesn't change m. I want m to be removed from the set that contains only empty tiles but I keep receiving a keyerror and I can't seem to figure out what the issue could be or where else it could be coming from.


Solution

  • You have a loop

    for d in domain[m].copy():
    

    where you are trying to tiles.remove(m) in every iteration. After it's removed in the first iteration, the dictionary won't have the key any more and you would get a keyerror in subsequent iterations.