I am relatively new in Python so facing difficulties in basics. I have following code that prints proper list value within loop but outside of loop it only shows the last value:
for item in statusEntries:
theNameStatus = item[3] #get the numStatus field data
if theNameStatus == 1:
numStatus1 = item[2] #get cntStatus
elif theNameStatus == 2:
if numStatus1 > 0:
theNameStatus = "closed"
sctStatus["nameStatus"] = theNameStatus
sctStatus["IDstatus"] = item[0]
sctStatus["cntStatus"] = item[2]
#Appending Status Array with Status Attribute Object
sctResponse["STATUSOPTION"].append(sctStatus)
When I print sctResponse[“STATUSOPTION”] within loop then it shows proper values with each iteration but when it reaches on last iteration it just fills it with last loop values:
{'STATUSOPTION': [{'nameStatus': 1, 'cntStatus': 0, 'IDstatus': 6}]}
{'STATUSOPTION': [{'nameStatus': 2, 'cntStatus': 0, 'IDstatus': 1}, {'nameStatus': 2, 'cntStatus': 0, 'IDstatus': 1}]}
{'STATUSOPTION': [{'nameStatus': 3, 'cntStatus': 0, 'IDstatus': 7}, {'nameStatus': 3, 'cntStatus': 0, 'IDstatus': 7}, {'nameStatus': 3, 'cntStatus': 0, 'IDstatus': 7}]}
{'STATUSOPTION': [{'nameStatus': 4, 'cntStatus': 0, 'IDstatus': 4}, {'nameStatus': 4, 'cntStatus': 0, 'IDstatus': 4}, {'nameStatus': 4, 'cntStatus': 0, 'IDstatus': 4}, {'nameStatus': 4, 'cntStatus': 0, 'IDstatus': 4}]}
{‘STATUSOPTION’: [{‘nameStatus’: 5, ‘cntStatus’: 0, ‘IDstatus’: 5}, {‘nameStatus’: 5, ‘cntStatus’: 0, ‘IDstatus’: 5}, {‘nameStatus’: 5, ‘cntStatus’: 0, ‘IDstatus’: 5}, {‘nameStatus’: 5, ‘cntStatus’: 0, ‘IDstatus’: 5}, {‘nameStatus’: 5, ‘cntStatus’: 0, ‘IDstatus’: 5}]}
As you can see the last bold record, all values wipied out and it filled it with last record. Why is it happening? Append should append rather than wiping it out, No?
Assuming that the loop is as you’ve shown it, then it looks to me like there’s only one
sctStatusdictionary, and you keep changing its"namestatus","IDstatus", and"cntStatus"key-value pairs. Try insertingsctStatus = {}, i.e.so that you’re appending a new dictionary each time.