I want to change one value in the dict of list, but the values with the same index of lists in the dictionary all change. I played around with it in terminal, and you can see two different displays with the same assigning way. https://ibb.co/fjWCCd
Sorry, I am not allowed to embed images yet. Or you can have a look down here
dict = {1:[0.0,0.0],2:[0.0,0.0]}
dict[1]
[0.0, 0.0]
dict[1][0]
0.0
dict[1][0]+=1
dict
{1: [1.0, 0.0], 2: [0.0, 0.0]}
dict[2][0] = 7
dict
{1: [1.0, 0.0], 2: [7, 0.0]}
dict[2][1] = 3
dict
{1: [1.0, 0.0], 2: [7, 3]}
std_log = [0.0,0.0]
thedict = {}
for i in range(8):
thedict[i+1] = std_log
thedict
{1: [0.0, 0.0], 2: [0.0, 0.0], 3: [0.0, 0.0], 4: [0.0, 0.0], 5: [0.0, 0.0], 6: [0.0, 0.0], 7: [0.0, 0.0], 8: [0.0, 0.0]}
thedict[2][1] = 6
thedict
{1: [0.0, 6], 2: [0.0, 6], 3: [0.0, 6], 4: [0.0, 6], 5: [0.0, 6], 6: [0.0, 6], 7: [0.0, 6], 8: [0.0, 6]}
newvalue = thedict[2]
newvalue
[0.0, 6]
newvalue[1]
6
newvalue[1] +=1
newvalue
[0.0, 7]
thedict[2] = newvalue
thedict
{1: [0.0, 7], 2: [0.0, 7], 3: [0.0, 7], 4: [0.0, 7], 5: [0.0, 7], 6: [0.0, 7], 7: [0.0, 7], 8: [0.0, 7]}
std_log = [0.0,0.0]
for i in range(8):
thedict[i+1] = std_log
This creates a dict where all keys are associated to the same list std_log
, so of course modifying one (key,value) pair will affect all other values (since they are the same object). Do this instead:
thedict = {i+1: [0.0,0.0] for i in range(8)}
This will create new lists for every single key, and you'll be able to modify them independently.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.