0
csv={“a”:0}
list_=[]
for i in range(2):
    csv["a"]+=1
    list_.append(csv)
    print(list_,csv)

I am getting output like this: [{'a': 2}, {'a': 2}]

I need to get an output like this [{'a': 1}, {'a': 2}]

Jiss Raphel
  • 365
  • 4
  • 15

2 Answers2

3

Because python pass variables to functions as reference and not as value, you need to pass a copy of the original dictionnary to list_.append():

csv={"a":0}
list_=[]
for i in range(2):
    csv["a"]+=1
    list_.append(dict(csv))
print(list_)
Cyphall
  • 348
  • 1
  • 10
2

You can do a list-comprehension:

list_ = [{'a': x} for x in range(1, 3)]
# [{'a': 1}, {'a': 2}]
Austin
  • 25,759
  • 4
  • 25
  • 48