简体   繁体   English

字典列表中的索引会影响所有字典

[英]Indexing in a list of dictionaries affects all the dictionaries

I made a list of dictionaries as below.我列出了如下字典。

num=5
core_dict ={'c1':[0]*num , 'c2':[0]*num}
link=[core_dict]*3

this gives the (correct) output:这给出了(正确的)output:

[ {'c1': [0, 0, 0, 0, 0], 'c2': [0, 0, 0, 0, 0]},  #represents link1 for me
  {'c1': [0, 0, 0, 0, 0], 'c2': [0, 0, 0, 0, 0]},  #represents link2 for me
  {'c1': [0, 0, 0, 0, 0], 'c2': [0, 0, 0, 0, 0]}]  #represents link3 for me

Then I want to replace the 'c1' values of link2.然后我想替换 link2 的'c1'值。 I do:我愿意:

link[1]['c1']=[10]*num

but this changes the values for the 'c1' key for every dictionary in the list.但这会更改列表中每个字典的'c1'键的值。 How can I do indexing to only affect one dictionary?我怎样才能做索引只影响一本字典?

[ {'c1': [10, 10, 10, 10, 10], 'c2': [0, 0, 0, 0, 0]},  #represents link1 for me
  {'c1': [10, 10, 10, 10, 10], 'c2': [0, 0, 0, 0, 0]},  #represents link2 for me
  {'c1': [10, 10, 10, 10, 10], 'c2': [0, 0, 0, 0, 0]}]  #represents link3 for me

Your initialization of link points every element to the same dictionary (ie the same location in memory):您的link初始化将每个元素指向同一个字典(即内存中的相同位置):

Instead of using:而不是使用:

link=[core_dict]*3

use利用

from copy import deepcopy
link=[deepcopy(core_dict) for _ in range(3)]

so that the memory used by each dictionary is completely separate.这样每个字典使用的memory就完全分开了。

You could also create link like this without importing deepcopy :您也可以在不导入deepcopy的情况下创建这样的link

link=[core_dict.copy() for i in range(3)]

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

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