Home > database >  Update dictionary value when key exists in list of tuples
Update dictionary value when key exists in list of tuples

Time:09-29

Variations of this question have been asked a lot, but I can't find an answer that addresses my query:

My list path_coords contains tuples which match keys in my dictionary grid I'm tring to change the value of each item in grid to 'X' if the key is present in path_coords

Example here works, as path_coords is a single tuple

# Define grid dimensions
width = 4
height = 4

# Grid dictionary
grid = {(0,0): "Y", (0,1): "Y", (0,2): "Y", (0,3): "Y",
        (1,0): "Y", (1,1): "Y", (1,2): "Y", (1,3): "Y",
        (2,0): "Y", (2,1): "Y", (2,2): "Y", (2,3): "Y",
        (3,0): "Y", (3,1): "Y", (3,2): "Y", (3,3): "Y"}

# Dictionary values to change
path_coords = (1,1)
grid[path_coords] = 'X'

# Create grid
for y in range(height):
    row = [grid[(y,x)] for x in range(width)]
    print(*row)

But this doesn't work, as the tuples are in a list?

# Define grid dimensions
width = 4
height = 4

# Grid dictionary
grid = {(0,0): "Y", (0,1): "Y", (0,2): "Y", (0,3): "Y",
        (1,0): "Y", (1,1): "Y", (1,2): "Y", (1,3): "Y",
        (2,0): "Y", (2,1): "Y", (2,2): "Y", (2,3): "Y",
        (3,0): "Y", (3,1): "Y", (3,2): "Y", (3,3): "Y"}

# Dictionary values to change
path_coords = [(1,1), (2,2)]
grid[path_coords] = 'X'

# Create grid
for y in range(height):
    row = [grid[(y,x)] for x in range(width)]
    print(*row)

I've tried a for loop, but get TypeError: unhashable type: 'list'

for path in path_coords:
    grid[path_coords] = 'X'

CodePudding user response:

I think this may be what you are aiming for?

width = 4
height = 4

# Grid dictionary
grid = {(0,0): "Y", (0,1): "Y", (0,2): "Y", (0,3): "Y",
        (1,0): "Y", (1,1): "Y", (1,2): "Y", (1,3): "Y",
        (2,0): "Y", (2,1): "Y", (2,2): "Y", (2,3): "Y",
        (3,0): "Y", (3,1): "Y", (3,2): "Y", (3,3): "Y"}

# Dictionary values to change
path_coords = [(1,1),(2,2)]
for coord in path_coords:
    grid[coord] = 'X'

# Create grid
for y in range(height):
    row = [grid[(y,x)] for x in range(width)]
    print(*row)
  • Related