简体   繁体   English

在 python 字典中填写值

[英]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.我希望这应该将“x”中的值填充为 {0., 10., 20., 30., 40.} 并且确实如此。 But it also fills in the same values for 'y' and 'z' which I don't want.但它也为 'y' 和 'z' 填充了我不想要的相同值。 Why is this happening and how can I prevent it?为什么会发生这种情况,我该如何预防?

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']}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM