1

In the following code, I created a simple dictionary, then I want to change the value of key B, but all the other values are changed,If the statement score.setdefault(name, values) is replaced by score.setdefault(name, [0,0,0]),then it works ok。I am so confused could somebody help me? Thank you very much.

names = ['A', 'B', 'C']
score = {}
values = [0,0,0]

#Create a dictionary: {'A': [0, 0, 0], 'B': [0, 0, 0], 'C': [0, 0, 0]}
for name in names:
    score.setdefault(name, values)
print(score)

#Change the value of key B
for name in names:
    score['B'][0] = 1
print(score)

#The result is: {'A': [1, 0, 0], 'B': [1, 0, 0], 'C': [1, 0, 0]}
jim
  • 11
  • 2
  • You mean you _don't_ want the lists associated to 'A' and 'C' to change, you only want the list associated to 'B' to change? In which case you could just use score.update({'B': [1,0,0]}) – Matthew Cassell Jun 23 '18 at 15:35
  • I edited the above code,score['B'][0] = 1is replaced by score.update({'B': [1,0,0]}),but it got the same result。 – jim Jun 23 '18 at 23:27
  • If the statement score.setdefault(name, values) is replaced by score.setdefault(name, [0,0,0]),then it works ok。I am so confused. – jim Jun 23 '18 at 23:29

0 Answers0