1 year ago

#388856

test-img

Yash54

Undesirable output when using fromkeys to initialize a dict with lists

I tried creating a 1D array of a grid point with values of x, and y as a list and then formed a dictionary to make a complete grid with some values stored w.r.t. each keys (grid point x,y), in this case, (0,0,0). Now when I add anything to a specific value to a specific key of that dictionary that value gets added to all the keys in the dictionary.

I wanted to know if there is any mistake that I am making or if it is something with the tuple keys, I couldn't find anything which specifies this behaviour.

#Define the lower and upper limits for x and y
minX = -1
maxX = 1
minY = -1
maxY = 1
#Spac=Spacing Between gridpoints
Spac = 1
cordinates = [(x,y) for x in np.linspace(minX, maxX, XSpac) for y in np.linspace(minY, maxY, YSpac)]

grid = dict.fromkeys(cordinates,[0,0,0])

pprint(grid)
grid[0.0,0.0][0] += 1
pprint(grid)

Output before operand(+=1)

{(-1.0, -1.0): [0, 0, 0],
 (-1.0, 0.0): [0, 0, 0],
 (-1.0, 1.0): [0, 0, 0],
 (0.0, -1.0): [0, 0, 0],
 (0.0, 0.0): [0, 0, 0],
 (0.0, 1.0): [0, 0, 0],
 (1.0, -1.0): [0, 0, 0],
 (1.0, 0.0): [0, 0, 0],
 (1.0, 1.0): [0, 0, 0]}

Output after operand(+=1)

{(-1.0, -1.0): [1, 0, 0],
 (-1.0, 0.0): [1, 0, 0],
 (-1.0, 1.0): [1, 0, 0],
 (0.0, -1.0): [1, 0, 0],
 (0.0, 0.0): [1, 0, 0],
 (0.0, 1.0): [1, 0, 0],
 (1.0, -1.0): [1, 0, 0],
 (1.0, 0.0): [1, 0, 0],
 (1.0, 1.0): [1, 0, 0]}

Required Output

{(-1.0, -1.0): [0, 0, 0],
     (-1.0, 0.0): [0, 0, 0],
     (-1.0, 1.0): [0, 0, 0],
     (0.0, -1.0): [0, 0, 0],
     (0.0, 0.0): [1, 0, 0],
     (0.0, 1.0): [0, 0, 0],
     (1.0, -1.0): [0, 0, 0],
     (1.0, 0.0): [0, 0, 0],
     (1.0, 1.0): [0, 0, 0]}

python

python-3.x

list

dictionary

0 Answers

Your Answer

Accepted video resources