2012-11-28 24 views
0

我在Python有代碼這需要將數據從數據庫andlooks這樣的:插入字典對象到一個數組的特定元素(的Python/Django的)

for result in request.user.results.all(): 
    data.append(dict([(str(word.type.type), str(word.word)) for word in result.word.all() 
    data.append(dict([(season, ResultForm.CHOICES[r.season][1])])) 

,其顯示「數據」爲:

[{'color': 'blue', 'kind': 'pencil', 'rating': 'high'}, {'color': 'red', 'kind': 'truck', 'rating': 'low'}, {'season': 'winter'}, {'season': 'spring'}] 

如何我只是調整了代碼,這樣數據的輸出看起來像:

[{'color': 'blue', 'kind': 'pencil', 'rating': 'high', 'season': 'winter'}, {'color': 'red', 'kind': 'truck', 'rating': 'low', 'season': 'spring'}] 

而不是僅僅插件g最後一個對象,將它添加到每個元素。

+0

我不知道。你怎麼知道你想要添加新數據到哪個字典? – Marcin

+0

它看起來像你想將季節鍵/值合併到結果字典中,但是如何知道'result.word.all()'與'score'的排序相同?你的第二個'data.append()'似乎並不是循環中的任何東西,除非'r.season'應該是'result.season'。即使如此,您提供的代碼片段也沒有說明爲什麼'score'應該以任何方式與您的結果查詢集相關聯。 – acjay

+0

對不起,分數應該是季節。 – ono

回答

0

我想你想在這裏dict.update。不過,我有點不能確定要插入dict.update,因爲我無法弄清楚你的代碼是如何工作 - 在我看來,你的輸出應該是這樣的:

[{'color': 'blue', 'kind': 'pencil', 'rating': 'high'}, {'season': 'winter'}, {'color': 'red', 'kind': 'truck', 'rating': 'low'}, {'season': 'spring'}] 

由於「季節」字典另一個( 「顏色」,等)的字典後立即加入...


作爲附帶說明:

dict([(score, ResultForm.CHOICES[r.season][1])]) 

寫入必須更加理解(並且有效地)爲:

{score: ResultForm.CHOICES[r.season][1]} 

如您的意見指出,我相信你想是這樣的:

for result in request.user.results.all(): 
    data.append(dict((str(word.type.type), str(word.word)) for word in result.word.all())) 
    data[-1].update({score: ResultForm.CHOICES[r.season][1]}) 
+0

我希望季節詞典包含在第一個詞典中,如我的第二個樣本集所示。 – ono

+0

但是哪一行創建「季節」字典?如果它是第二個'data.append'行,那麼我相信你說你得到的結果的順序是錯誤的。 – mgilson

+0

是的,很抱歉,沒有說清楚;它是第二個追加創建季節 – ono

相關問題