1

I meet a problem when trying to continuously add modified dictionaries into the same list. I simplified what I want to do below:

a = {"1":"1"}
b = [a]

for i in range (2,5):
 a["1"] = i
 b.append(a)

print(b)

This will give me

[{'1': 4}, {'1': 4}, {'1': 4}, {'1': 4}]

But I want b as

[{'1': 1}, {'1': 2}, {'1': 3}, {'1': 4}]

How should I do this?

lyj
  • 23
  • 2

1 Answers1

0

Do not reuse the "a" dict inside the loop and create a new small dict each time it is needed You can do like this:

a = {"1":"1"}
b = [a]

for i in range (2,5):
    b.append({"1":i})

print(b)

the result is :

[{'1': '1'}, {'1': 2}, {'1': 3}, {'1': 4}]
Malo
  • 1,233
  • 1
  • 8
  • 25