Home > database >  Why is Dictionary lookup causing 'unhashable type' error, but using direct values doesn�
Why is Dictionary lookup causing 'unhashable type' error, but using direct values doesn�

Time:11-02

I am trying to improve some code using a dictionary lookup rather than by using cumbersome multiple if statements. However, when I try to run the code using the variables derived the code returns a "TypeError: unhashable type", but if I run the same code but instead use direct values rather than the derived values, the code runs.

This is the code that fails:

def colour_check_under_mouse():
 global d_colours
 mouse_pos = pygame.mouse.get_pos()
 if pygame.mouse.get_pressed()[0]:
    colour_under_mouse = pygame.Surface.get_at(screen, mouse_pos)
    print(colour_under_mouse)
    colour_selected = d_colours[colour_under_mouse]
    # colour_selected = d_colours[255, 0, 0, 255]
    print(colour_selected)

And after alternating the commented out line to one with hard coded values, this is the code that runs:

def colour_check_under_mouse():
 global d_colours
 mouse_pos = pygame.mouse.get_pos()
 if pygame.mouse.get_pressed()[0]:
    colour_under_mouse = pygame.Surface.get_at(screen, mouse_pos)
    print(colour_under_mouse)
    # colour_selected = d_colours[colour_under_mouse]
    colour_selected = d_colours[255, 0, 0, 255]
    print(colour_selected)

The dictionary used is:

d_colours = {(255, 0, 0, 255): 'Red', (0, 255, 0, 255): 'Green', (0, 0, 255, 255): 'Blue', (255, 255, 0, 255): 'Yellow'}

I am confused as to why the code runs successfully when I hard code the very same values in the colour_selected = line as those returned in the code above. I understand what an unhashable type is, but could someone help me understand what is changing within the two lines that results in one line causing that error please. Cheers.

CodePudding user response:

With what I see in the documentation for PyGame (link) the part of the code you are using:

pygame.Surface.get_at

returns a color instead of the tuple. Try using:

colour_under_mouse = tuple(pygame.Surface.get_at(screen, mouse_pos))
  • Related