0

I am running into a problem with repeated values being inserted into a list of dictionaries. I only want to update one of these dictionaries with the key and value information below. Why is it updating all of them in the list?

>>> d = [{}]*3
>>> d
[{}, {}, {}]
>>> d[0]
{}
>>> d[0]['one'] = 1
>>> d
[{'one': 1}, {'one': 1}, {'one': 1}]

Any help is appreciated, thank you!

  • 2
    That is pretty much the same as doing `d = [a]*3`. You are passing three references to the same empty dict. – OTheDev Apr 15 '22 at 17:40
  • 1
    Because `d = [{}]*3` creates a list with *three references to the same `dict`*. So imagine you did `mylist = []; mydict = {}; mylist.append(mydict); mylist.append(mydict); mylist.append(mydict)` and you'll see the same behavior – juanpa.arrivillaga Apr 15 '22 at 17:41
  • 1
    [This](https://stackoverflow.com/questions/3975376/understanding-dict-copy-shallow-or-deep) might help you with python dictionaries and how they are references. – Rashid 'Lee' Ibrahim Apr 15 '22 at 17:41
  • By the way, you can just do `d = [{} for i in range(3)]` – OTheDev Apr 15 '22 at 17:43

0 Answers0