0

I want to declare a list of n dictionary. Nevertheless, during iteration, all dictionaries in the list seem to point to the same dictionary. The data of the last iteration applying to all dictionaries in the list. How to avoid this problem? Thank you

lst=[]
template={"field1":"","field2":"","field3":""}
j={}
dict_id=1
for i in range(10):
    j[dict_id]=template
    j[dict_id]["field1"]=i
    j[dict_id]["field2"] = i
    j[dict_id]["field3"] = i
    dict_id+=1
    lst.append(j)

print(j)

  >>> 
   {1: {'field1': 9, 'field2': 9, 'field3': 9},
    2: {'field1': 9, 'field2': 9, 'field3': 9},
    3: {'field1': 9, 'field2': 9, 'field3': 9},
    4: {'field1': 9, 'field2': 9, 'field3': 9},
    5: {'field1': 9, 'field2': 9, 'field3': 9},
    6: {'field1': 9, 'field2': 9, 'field3': 9},
    7: {'field1': 9, 'field2': 9, 'field3': 9},
    8: {'field1': 9, 'field2': 9, 'field3': 9},
    9: {'field1': 9, 'field2': 9, 'field3': 9},
   10: {'field1': 9, 'field2': 9, 'field3': 9}}

0 Answers0