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
.