Search code examples
pythondictionarykeyerror

KeyError when key is in dictionary


So I stumbled upon this weird bug. I made a dictionary that contains these keys:

database_5x5 = {'(1, 0, 0, 0, 1)': [(0, 0), (0, 1)],
                '(0, 1, 0, 1, 0)': [(0, 0), (0, 3)],
                '(1, 1, 1, 0, 0)': [(0, 1)],
                '(0, 0, 1, 1, 1)': [(0, 3)],
                '(1, 0, 1, 1, 0)': [(0, 4)],
                '(0, 1, 1, 0, 1)': [(0, 0)],
                '(1, 1, 0, 1, 1)': [(0, 2)]
                }

This is the code that accesses the dictionary:

 bottom = tuple(puzzle[len(puzzle)-1])
    next_moves = database_5x5[bottom]

My code runs and gives me this error:

KeyError: (0, 1, 1, 0, 1)

I'm not sure what could be wrong here... I appreciate the help!


Solution

  • Keys in the dictionary are of type string. You should cast bottom:

    next_moves = database_5x5[str(bottom)]