Reputation: 165
I have the following example code
test_dict = dict.fromkeys(['x','y','z'], np.zeros(5))
for j in range(5):
test_dict['x'][j]= j*10
print(test_dict)
I expect that this should fill in the value in 'x' as {0., 10., 20., 30., 40.} and it does. But it also fills in the same values for 'y' and 'z' which I don't want. Why is this happening and how can I prevent it?
Upvotes: 1
Views: 285
Reputation: 71574
Your dictionary keys all point to the same value. Try initializing it with a comprehension instead:
test_dict = {key: np.zeros(5) for key in ['x', 'y', 'z']}
Upvotes: 3