My code is as follows : I have string that has header data and want create lists of dictionary with same keys values being created as a new list.
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
Output obtained :
{Type: 0,Record Size: 0x30,id: 0x3,Version: 0x3,Bas : 0x3,Size: 0x30}
Expected output:
{{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}}
Currently only last key value is obtained, its over-writing into only one list, while wanted 3 lists to be displayed.
Advertisement
Answer
You are repeatedly updating the same dictionary – you need to create a new dictionary at each iteration and append it to a list
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)