我在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最後一個對象,將它添加到每個元素。
我不知道。你怎麼知道你想要添加新數據到哪個字典? – Marcin
它看起來像你想將季節鍵/值合併到結果字典中,但是如何知道'result.word.all()'與'score'的排序相同?你的第二個'data.append()'似乎並不是循環中的任何東西,除非'r.season'應該是'result.season'。即使如此,您提供的代碼片段也沒有說明爲什麼'score'應該以任何方式與您的結果查詢集相關聯。 – acjay
對不起,分數應該是季節。 – ono