1

This behavior in Python 3.7.2 (did not check other versions) surprises me. The goal is to have a list of dictionaries with the same keys and be able to manipulate individual values. Using list index and dictionary key, the expected behavior is that I should be able to set value of a key of a specific dictionary.

Here's a sample code:

    lst = []

    lst.append({"A" : 0, "B" : 0 })
    lst.append({"A" : 0, "B" : 0 })

    lst[1]["B"] = 11
    print(lst)

    lst2 = [{"A" : 0, "B" : 0 }]*2

    lst2[1]["B"] = 11
    print(lst2)

Here's the result:

[{'A': 0, 'B': 0}, {'A': 0, 'B': 11}]
[{'A': 0, 'B': 11}, {'A': 0, 'B': 11}]

The second result surprises me, why would it set value of key "B" to 11 for both dictionaries? Why is there a difference between initializing as lst and lst1.

thch23
  • 11
  • 2
  • 1
    Because in the second list, `lst2[0]` and `lst2[1]` both reference the same dictionary, while in the first case, you created two separate ones. – Thierry Lathuille Nov 10 '19 at 19:27

1 Answers1

0

If you duplicate the dictionary - either the way you did, or a = b = {'someKey': 'someValue'}, you only copy the reference, and not the object itself. Changing the object through the reference will reflect the changes in the other references of the same object.

CoderCharmander
  • 1,862
  • 10
  • 18