1

Sorry if this is a basic Python question, but for some reason, I can't figure this out.

Suppose I create a list of a list of a dictionary,

b=[[{'j':1}]*3]*3

so that "b" is this:

[[{'j': 1}, {'j': 1}, {'j': 1}],
[{'j': 1}, {'j': 1}, {'j': 1}],
[{'j': 1}, {'j': 1}, {'j': 1}]] 

Now suppose I want to change "b" to:

[[{'j': 1}, {'j': 1}, {'j': 1}],
[{'j': 1}, {'j': 1}, {'j': 90}],
[{'j': 1}, {'j': 1}, {'j': 1}]] 

so I naively use this line of code

b[1][2]['j']=90

However, "b" is now this:

[[{'j': 90}, {'j': 90}, {'j': 90}],
[{'j': 90}, {'j': 90}, {'j': 90}],
[{'j': 90}, {'j': 90}, {'j': 90}]] 

Why did all of the dictionaries in the list of a list change? Why didn't only the b[1][2] entry change?

Also, the lines

b=[[{'j':1}]*3]*3
b[1][2]={'j':90} 

changes "b" to

[[{'j': 1}, {'j': 1}, {'j': 90}],
[{'j': 1}, {'j': 1}, {'j': 90}],
[{'j': 1}, {'j': 1}, {'j': 90}]] 

which I also can't explain.

ChickenGod
  • 113
  • 4

1 Answers1

2

You need to use the dictionary's copy() command, or else you are creating multiple references to the same dictionary.

Try something like this:

>>> c = {'j':1}
>>> b = [c, c.copy(), c.copy()]
>>> b
[{'j': 1}, {'j': 1}, {'j': 1}]
>>> b[2]['j']=2
>>> b
[{'j': 1}, {'j': 1}, {'j': 2}]
Kevin
  • 2,112
  • 14
  • 15