0

I have a 2D jagged list/ list of lists where each entry is dictionary. I only want to change one value but when I try it I change every value in the list.

#initialise 
startValue = {"a":0, "b":1, "c":2}
myList = [[startValue for i in range(3)] for j in range(3)]
print(myList)

#change one item
myList[1][1]["a"] = 5
print(myList)

The output is

[[{'a': 0, 'b': 1, 'c': 2}, {'a': 0, 'b': 1, 'c': 2}, {'a': 0, 'b': 1, 'c': 2}], [{'a': 0, 'b': 1, 'c': 2}, {'a': 0, 'b': 1, 'c': 2}, {'a': 0, 'b': 1, 'c': 2}], [{'a': 0, 'b': 1, 'c': 2}, {'a': 0, 'b': 1, 'c': 2}, {'a': 0, 'b': 1, 'c': 2}]]
[[{'a': 5, 'b': 1, 'c': 2}, {'a': 5, 'b': 1, 'c': 2}, {'a': 5, 'b': 1, 'c': 2}], [{'a': 5, 'b': 1, 'c': 2}, {'a': 5, 'b': 1, 'c': 2}, {'a': 5, 'b': 1, 'c': 2}], [{'a': 5, 'b': 1, 'c': 2}, {'a': 5, 'b': 1, 'c': 2}, {'a': 5, 'b': 1, 'c': 2}]]

Every value of "a" in the list has changed to 5. Would be very grateful to know how to change just one value. I think it is a common problem but could not find a solution.

Note that this is a dictionary in a 2D jagged list. It is not a dictionary in a dictionary nor a list in a list so is not a duplicate of these question as has been claimed and the potential solution would not be the same.

Tman
  • 11
  • 2
  • 2
    Add `.copy()` method to the `startValue` variable in the list comprehension, that way all the dictionaries are different objects. – ChrisOram Jul 15 '21 at 13:18
  • Because you put **the same dictionary in all your sublists**. Don't do that, put a *new* dictionary in each sublist – juanpa.arrivillaga Jul 15 '21 at 20:55
  • "Note that this is a dictionary in a 2D jagged list. It is not a dictionary in a dictionary nor a list in a list so is not a duplicate of these question as has been claimed and the potential solution would not be the same." The solution is exactly the same because it is the same fundamental problem, hence it is a duplicate. – juanpa.arrivillaga Jul 15 '21 at 20:55
  • And note, lists *do not have dimensions*. Lists are sequences of Python objects. – juanpa.arrivillaga Jul 15 '21 at 20:55

0 Answers0