How to grow a list of dictionaries in Python

Question:

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?

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.

Asked By: Robert Alexander

||

Answers:

mydict = {}
mylist = []

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

mydict = {}  # This is a second dictionary

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

print(mylist)

You’ll get:

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

Answered By: David Rubio
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:

Answered By: FLAK-ZOSO
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.