你好,我正在嘗試創建一個像這樣的字典
{104: {'tid': 1234, 'date': '08/26/2022', 'total': '95.96'}, {'tid': 1235, 'date': '09/25/2022', 'total': '95.96'}, {'tid': 1236, 'date': '07/27/2022', 'total': '95.96'}}
{105: {'tid': 1237, 'date': '08/26/2022', 'total': '85.96'}, {'tid': 1238, 'date': '09/25/2022', 'total': '85.96'}, {'tid': 1238, 'date': '07/27/2022', 'total': '85.96'}}
我正在查詢的資料庫中有以下內容
CID || TID || DATE || TOTAL
104 1234 08/26/2022 95.96
104 1235 09/25/2022 95.96
104 1236 07/27/2022 95.96
105 1237 08/26/2022 85.96
105 1238 09/25/2022 85.96
105 1239 07/27/2022 85.96
我有以下代碼來遍歷查詢結果并創建一個字典,但它并沒有像我想要的那樣創建它 o
outer_dict = {}
records = cursor.fetchall()
for i in records:
inner_dict = {"tid":i[1], "date": i[2], "total": i[3]}
outer_dict[i[0]] = inner_dict
任何幫助將不勝感激。
uj5u.com熱心網友回復:
我只能想象你真正想要的是這樣的:
{
104: [
{'tid': 1234, 'date': '08/26/2022', 'total': '95.96'},
{'tid': 1235, 'date': '09/25/2022', 'total': '95.96'},
{'tid': 1236, 'date': '07/27/2022', 'total': '95.96'}
],
105: [
{'tid': 1237, 'date': '08/26/2022', 'total': '85.96'},
{'tid': 1238, 'date': '09/25/2022', 'total': '85.96'},
{'tid': 1238, 'date': '07/27/2022', 'total': '85.96'}
]
}
這是如何獲得的:
outer_dict = {}
records = cursor.fetchall()
for i in records:
inner_dict = {"tid": i[1], "date": i[2], "total": i[3]}
outer_dict[i[0]] = outer_dict.get(i[0], []) [inner_dict]
最后一行是唯一的區別。.get()獲取給定字典鍵的值,在本例中是已經存在的串列,或者鍵不存在時的默認值,在本例中是一個新的空串列。然后它將新的 inner_dict 附加到串列中,并將該鍵的字典值設定到結果串列中。
順便說一句:直接回圈遍歷記錄for i in records:是正確的方法,但是您可能不應該i在這里命名回圈變數,因為i它通常用于索引回圈變數。類似row或rec似乎在這里更合適,并且不太可能引起讀者(包括未來的你)的混淆。
編輯:您正確地指出 using.append()會導致錯誤,因為它不會回傳串列本身。更新后的答案與廣告一樣有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/534507.html
標籤:Python字典
