Daniel
Daniel

Reputation: 165

Filling in values in python dictionary

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

Answers (1)

Samwise
Samwise

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

Related Questions