[英]Create new list within dictionary of lists if the same keys are there in a string
我的代碼如下:我有一個包含標題數據的字符串,並希望創建具有相同鍵值的字典列表,並將其創建為新列表。
header ="Type : 0 Record Size : 0x10 id : 0x1 Version : 0x1 Bas : 0x1 Size : 0x10\
Type : 0 Record Size : 0x20 id : 0x2 Version : 0x2 Bas : 0x2 Size : 0x20\
Type : 0 Record Size: 0x30 id : 0x3 Version : 0x3 Bas : 0x3 Size : 0x30"
data_hb = {}
for line in header.split("\n"):
if len(line) > 0 and len(line.split(":")) > 1:
key, value = line.split(":")
key = key.strip()
value = value.strip()
data_hb[key] = value
獲得的輸出:
{Type: 0,Record Size: 0x30,id: 0x3,Version: 0x3,Bas : 0x3,Size: 0x30}
預期輸出:
{{Type: 0,Record Size: 0x10,id: 0x1,Version: 0x1,Bas: 0x1,Size: 0x10},
{Type: 0,Record Size: 0x20,id: 0x2,Version: 0x2,Bas: 0x2,Size: 0x20},
{Type: 0,Record Size: 0x30,id: 0x3,Version: 0x3,Bas: 0x3,Size: 0x30}}
目前只獲取最后一個鍵值,它只覆蓋到一個列表中,而想要顯示 3 個列表。
您重復更新同一個字典 - 您需要在每次迭代時創建一個新字典並將其附加到列表中
data_hb_list = []
for line in header.split("\n"):
data_hb = {}
if len(line) > 0 and len(line.split(":")) > 1:
key, value = line.split(":")
key = key.strip()
value = value.strip()
data_hb[key] = value
data_hb_list.append(data_hb)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.