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.
JavaScript
x
12
12
1
header ="Type : 0 Record Size : 0x10 id : 0x1 Version : 0x1 Bas : 0x1 Size : 0x10
2
Type : 0 Record Size : 0x20 id : 0x2 Version : 0x2 Bas : 0x2 Size : 0x20
3
Type : 0 Record Size: 0x30 id : 0x3 Version : 0x3 Bas : 0x3 Size : 0x30"
4
5
data_hb = {}
6
for line in header.split("n"):
7
if len(line) > 0 and len(line.split(":")) > 1:
8
key, value = line.split(":")
9
key = key.strip()
10
value = value.strip()
11
data_hb[key] = value
12
Output obtained :
JavaScript
1
2
1
{Type: 0,Record Size: 0x30,id: 0x3,Version: 0x3,Bas : 0x3,Size: 0x30}
2
Expected output:
JavaScript
1
4
1
{{Type: 0,Record Size: 0x10,id: 0x1,Version: 0x1,Bas: 0x1,Size: 0x10},
2
{Type: 0,Record Size: 0x20,id: 0x2,Version: 0x2,Bas: 0x2,Size: 0x20},
3
{Type: 0,Record Size: 0x30,id: 0x3,Version: 0x3,Bas: 0x3,Size: 0x30}}
4
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
JavaScript
1
10
10
1
data_hb_list = []
2
for line in header.split("n"):
3
data_hb = {}
4
if len(line) > 0 and len(line.split(":")) > 1:
5
key, value = line.split(":")
6
key = key.strip()
7
value = value.strip()
8
data_hb[key] = value
9
data_hb_list.append(data_hb)
10