[Tutor] TypeError: unhashable type: 'pygame.math.Vector2'

Mats Wichmann mats at wichmann.us
Thu Jun 25 12:06:04 EDT 2020


On 6/25/20 8:56 AM, Cravan wrote:
> Hi all,
> 
>                 I recently embarked on learning Q-learning in python, but got an error that I’ve no idea how to fix. So here’s my code in one of my .py files: 

> However when I run the second file I encounter an error:
> 
> Traceback (most recent call last):
>   File "maze.py", line 170, in <module>
>     action = maxAction(Q, observationnew, possible_actions)
>   File "maze.py", line 136, in maxAction
>     values = np.array([Q[state,a] for a in actions])
>   File "maze.py", line 136, in <listcomp>
>     values = np.array([Q[state,a] for a in actions])
> TypeError: unhashable type: 'pygame.math.Vector2'

a TypeError generically means you are using an incompatible data type in
place which has a restriction on what types can be used.

Your Q is a dictionary;

    Q = {}

and dicts specifically have the restriction that the type be hashable
(meaning it must be a type that doesn't change during runtime, like a
list - or a 2d Vector in your case), because when a key is inserted into
the dict, Python stores the hash of it for later lookups, and if, later,
it would hash differently because it has changed, the lookup wouldn't work.

the "state" you pass to maxAction, where the error was raised, looks
like it's probably a vector since it sounds like it represents a position:

            observation = zomb.pos
            action = maxAction(Q, observation, zomb.possibleActions) if
rand < (1-EPS) \
                                                        else
zomb.actionSpaceSample()

if zomb.pos was indeed a Vector2, then indexing Q using that as part of
the (state, a) tuple is the cause of your problem. Are you sure it's a
position you wanted to pass in this call?

     values = np.array([Q[state,a] for a in actions])



More information about the Tutor mailing list