List of dictionaries created by loop - problem to change value

1970 views python
0

I created list of dictionaries using loop like this:

some_dict = {'Color': 'Red'}
list_of_dict = []
n = 3

for i in range(n):
    list_of_dict.append(some_dict)

But when I want now change value of the first dictionary it changes this value in each dictionary of the list.

list_of_dict[0]['Color'] = 'Blue'
print(list_of_dict)

Expected output is:

[{'Color': 'Blue'}, {'Color': 'Red'}, {'Color': 'Red'}]

But what I actually get is that:

[{'Color': 'Blue'}, {'Color': 'Blue'}, {'Color': 'Blue'}]

Please help me if you can.

answered question

To the downvoter: You might be bit harsh. This is a post by a new user with a Minimal, Complete, and Verifiable example. Everything is runnable and we have input, expected output and actual output.

1 Answer

9

Appending to a list does not copy any data - you are appending literally the same object in memory three times to your list.

However, your code can be easily fixed by using

list_of_dict.append(some_dict.copy())

in the loop's body.

See How to copy a dictionary and only edit the copy for more information.

posted this

Have an answer?

JD

Please login first before posting an answer.