Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create new list within dictionary of lists if the same keys are there in a string

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{{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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading