0

I'm attempting to build a data structure that can change in size and be posted to Firebase. The issue I am seeing is during the construction of the data structure. I have the following code written:

for i in range(len(results)):
designData = {"Design Flag" : results[i][5],
        "performance" : results[i][6]}
for j in range(len(objectiveNameArray)):
    objectives[objectiveNameArray[j]] = results[i][columnHeaders.index(objectiveNameArray[j])]
designData["objectives"] = copy.copy(objectives)
for k in range(len(variableNameArray)):
    variables[variableNameArray[k]] = results[i][columnHeaders.index(variableNameArray[k])]
designData["variables"] = copy.copy(variables)
for l in range(len(responseNameArray)):
    responses[responseNameArray[l]] = results[i][columnHeaders.index(responseNameArray[l])]
designData["responses"] = copy.copy(responses)
for m in range(len(constraintNameArray)):
    constraintViolated = False
    if constraintNameArray[m][1] == "More than":
        if results[i][columnHeaders.index(constraintNameArray[m][0])] > constraintNameArray[m][2]:
            constraintViolated = True
        else:
            constraintViolated = False
    elif constraintNameArray[m][1] == "Less than":
        if results[i][columnHeaders.index(constraintNameArray[m][0])] < constraintNameArray[m][2]:
            constraintViolated = True
        else:
            constraintViolated = False
    if constraintNameArray[m][0] in constraints:
        if constraints[constraintNameArray[m][0]]["violated"] == True:
            constraintViolated = True
    constraints[constraintNameArray[m][0]] = {"value" : results[i][columnHeaders.index(constraintNameArray[m][0])], "violated" : constraintViolated}
designData["constraints"] = copy.copy(constraints)
data[studyName][results[i][4]] = designData

When I include print(designData) inside of the for loop, I see that my results are changing as expected for each loop iteration.

However, if I include print(data) outside of the for loop, I get a data structure where the values added by the results array are all the same values for each iteration of the loop even though the key is different.

Comparing print(data) and print(designData)

I apologize in advance if this isn't enough information this is my first post on Stack so please be patient with me.

  • 1
    I highly recommend posting your code snippet in the main body of the question if you want to get useful replies. – Sohier Dane Sep 27 '16 at 00:35

1 Answers1

0

It is probably because you put the variables like objectives, variables, responses directly to the designData. Try the following:

import copy

....
designData['objectives'] = copy.copy(objectives)
....
designData['variables'] = copy.copy(variables)
....
designData['responses'] = copy.copy(responses)

For similar questions, see copy a list.

Community
  • 1
  • 1
mengg
  • 310
  • 2
  • 9