-1

In python, I want to make a 2D array with dictionaries. I do have knowledge of references, so I explicitly used .copy. When I print the array out, however, the dictionaries that I do not want to be changed also changes. My code is below.

dicts = []
for j in range(3):
    dicts.append([{0:0,1:0,2:0,3:0}.copy()].copy() * 3)

dicts[0][0][0] = 5
dicts[1][1][0] = 10
print(dicts)

OUTPUT:

[[{0: 5, 1: 0}, {0: 5, 1: 0}], [{0: 0, 1: 10}, {0: 0, 1: 10}]]

Does anyone know why this happens, and anyway to fix it? Thank you.

  • See the duplicate, and note that using `copy` this way doesn't change anything, as you still get 3 times the same dict object. – Thierry Lathuille Dec 28 '21 at 23:55
  • None of your calls to `copy` are useful. You are just working with references to *copies* of the objects created by the displays, rather than the originals. – chepner Dec 28 '21 at 23:55

1 Answers1

0

The way to solve this kind of thing cleanly is with list comprehensions:

dicts = [[{0:0,1:0,2:0,3:0} for i in range(3)] for j in range(3)]
dicts[0][0][0] = 5
dicts[1][1][0] = 10
print(dicts)

Output:

[[{0: 5, 1: 0, 2: 0, 3: 0}, {0: 0, 1: 0, 2: 0, 3: 0}, {0: 0, 1: 0, 2: 0, 3: 0}], [{0: 0, 1: 0, 2: 0, 3: 0}, {0: 10, 1: 0, 2: 0, 3: 0}, {0: 0, 1: 0, 2: 0, 3: 0}], [{0: 0, 1: 0, 2: 0, 3: 0}, {0: 0, 1: 0, 2: 0, 3: 0}, {0: 0, 1: 0, 2: 0, 3: 0}]]
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • Weird. This question was closed quite a while before your answer was posted. (I posted my comment on the question after it was closed while typing up my own answer.) – chepner Dec 29 '21 at 00:05
  • I noticed that after I answered and felt slightly guilty. Not sure why it worked. – Tim Roberts Dec 29 '21 at 00:13
  • I should say, nothing wrong with your answer at all, just surprised it slipped through :) – chepner Dec 29 '21 at 00:14