Cris Austin Cris Austin - 1 year ago 152
Python Question

python: append dict into list issue

I'm actually new on python. With exam code, I found something strange

Here's my code.

cat_log = []
container = {}
for index in range(10) :
container["idx"] = index
cat_log.append(container)
print(cat_log)


I want the result like this: [{'idx' : 0 } , { 'idx' : 1 } , { 'idx' : 2 } , { 'idx' : 3 }].
But my code doesn't output this result.
Something like this: [{ 'idx' : 3 } , { 'idx' : 3 } , { 'idx' : 3 } , { 'idx' : 3 }]
I've googled why this happens, but I didn't find any right idea.
What's wrong and why?

Answer Source

When you append container you are not making a copy, so you are just appending a reference to the same dict over and over. You are mutating the dict as well and you cannot have multiple values of the same key in a dictionary, it is just overwriting idx with the current index each time.

Instead, append a new dictionary each iteration. Eg:

cat_log = []
for index in range(10) : 
    cat_log.append({"idx": index})
print(cat_log)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download