Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python: not able to grow a list of dictionaries

The following demo code:

mydict = {}
mylist = []

mydict["s"] = 1
mydict["p"] = "hasprice"
mydict["o"] = 3
print(mydict)
mylist.append(mydict)

mydict["s"] = 22
mydict["p"] = "hasvat"
mydict["o"] = 66
print(mydict)
mylist.append(mydict)

print(mylist)

prints out the following result:

[{'s': 22, 'p': 'hasvat', 'o': 66}, {'s': 22, 'p': 'hasvat', 'o': 66}]

and the only explanation that comes to my mind is that mydict is assigned by reference and therefore the list items all point to a same memory object. Is this the reason?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I properly append multiple different dictionaries to the list?

I am building each mydict dictionary within a loop and then wanted to append it to the list which I will finally write to a JSON file. Thanks.

>Solution :

mylist.append(mydict)

So, what are you doing here? You’re appending a dict object, right?

The problem is that in Python the dict is a mutable type, which gets passed by reference.

That’s why when you edit mydict you’re also editing mylist[0], because they both reference to the same object.


To achieve what I think you want to do, simply do this instead:

mylist.append(mydict.copy())

This creates a copy which no more refers to mydict.

The copy should be done when first calling .append, otherwise you’ll anyway get two identical dicts, as @sj95126 pointed out.


To better understand my answer, I strongly suggest to read the following:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading