Home > Mobile >  Indexing in a list of dictionaries affects all the dictionaries
Indexing in a list of dictionaries affects all the dictionaries

Time:04-09

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:

[ {'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. I do:

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

but this changes the values for the 'c1' key for every dictionary in the list. 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

CodePudding user response:

Your initialization of link points every element to the same dictionary (i.e. the same location in memory):

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.

CodePudding user response:

You could also create link like this without importing deepcopy:

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