0

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]}
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Yash54
  • 3
  • 2
  • Side-note: Using `float`s as part of the keys in a `dict` is *extremely* risky; in this case, they're all really fixed integer values chosen from a set of three, but if you try to compute those values in a different way when looking things up, your math might be logically correct but by virtue of being done a different way with imprecise floating point, it might produce a subtly incorrect value and not be found on lookup. – ShadowRanger Apr 07 '22 at 19:51
  • okay, I wasn't aware of this. Thanks a lot . – Yash54 Apr 08 '22 at 04:29

0 Answers0