Reputation: 59
I am coding a chess program and am coding check. I need the key from the opponent moves dictionary (which contains the king's position) to be used to find the coordinate of the piece placing it in check. Right now this is givng me the error:
opponentpieceposition=opponentposition.get(piece)
TypeError: unhashable type: 'list'.
Note the example below should print (1,6)
king=(5,1)
opponentmoves={'ksknight': [(8, 3), (5, 2), (6, 3)],
'ksbishop': [(3, 6), (4, 7), (5, 8), (1, 4), (1, 6), (3, 4), (4, 3), (5, 1), (6, 1)],
'king': [(6, 1), (5, 2), (4, 1)],
'queen': [(4, 5), (2, 4), (1, 3), (2, 6), (1, 7), (4, 4)],
'qsknight': [(3, 3), (1, 3)]}
opponentposition={'ksknight': (1, 3),
'ksbishop': (1, 6),
'king': (6, 1),
'queen': (4, 5),
'qsknight': (3, 3)}
if king in [z for v in opponentmoves.values() for z in v]:
piece=[key for key in opponentmoves if king in opponentmoves[key]]
opponentpieceposition=opponentposition.get(piece)
print(opponentpieceposition)
Upvotes: 1
Views: 160
Reputation: 59
This is what I got working.
if king in [z for v in opponent.moves.values() for z in v]:
for key in opponent.moves:
opponentpiece=opponent.moves[key]
if king in opponentpiece:
opponentposition=opponent.position[key]
Upvotes: 0
Reputation: 3826
In your code piece is a list, it can't be dictionary key. Please follow comments in code how to overcome the issue:
if king in [z for v in opponentmoves.values() for z in v]:
piece = [key for key in opponentmoves if king in opponentmoves[key]]
print(piece) # Let's show what is piece
# result is ['ksbishop']
# so we need 1st element of the list pice
opponentpieceposition=opponentposition.get(piece[0]) # take the 1st element
print(opponentpieceposition)
Hope it helped to solve the issue.
Upvotes: 1
Reputation: 561
lists and objects of other mutable types cannot be used as keys in dictionaries (or elements in sets).
These containers rely on computing a hash value which is a function of the 'content' of the object at insertion time. So if the object (like mutable objects are able to) changes after insertion there will be problems.
you can instead use a tuple which is an immutable sequence.
Upvotes: 1