2016-09-27 67 views
0

我試圖構建一個數據結構,可以改變大小併發布到Firebase。我看到的問題是在數據結構的構建過程中。我有以下的代碼寫成:Python創建詞典結構的字典,嵌套值是一樣的

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 

當我包括for循環,我認爲這是預期的每次循環迭代我的成果正在改變內印刷(designData)。但是,如果我在for循環之外包含print(data),我會得到一個數據結構,其中由結果數組添加的值對於循環的每次迭代都是相同的值,即使該鍵不同也是如此。

Comparing print(data) and print(designData)

我提前道歉,如果這是不足夠的信息,這是我對堆棧的第一篇文章,所以請耐心等待我。

+1

如果您想獲得有用的回覆,我強烈建議在問題的主體中張貼您的代碼片段。 –

回答

0

這可能是因爲您將objectives,variables,responses這些變量直接輸入designData。請嘗試以下操作:

import copy 

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

對於類似的問題,請參閱copy a list

+0

工作。感謝您的幫助。 –