data = []
dic = dict.fromkeys(['a', 'b', 'c'], 0)
value = 1
for i in range(3):
key = list(dic.keys())
for j in range(len(dic)):
dic[key[j]] = value
value += 1
data.append(dic)
for i in data:
print(i)
In this code, I expexted like this.
{1, 2, 3}
{4, 5, 6}
{7, 8, 9}
but the result is
{7, 8, 9}
{7, 8, 9}
{7, 8, 9}
How can i fix this code to get result that i expected?
>Solution :
Instead of :
data.append(dic)
Use:
data.append(dic.copy())
This will create a new object, instead of adding a reference to dic to your list.