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

How to group data separated by empty lines

I have a file that I wanted to group into list. The data are separated by empty lines. How to parse the data properly to get the needed output?

mydata.txt

introA
aboutA1
aboutA2
aboutA3
aboutA4

introB
aboutB1
aboutB2
aboutB3
aboutB4

Current Code:

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

with open("mydata.txt", "r") as f:
    data = [line.strip() for line in f if line.strip()]

print (data)

Current Output:

['introA', 'aboutA1', 'aboutA2', 'aboutA3', 'aboutA4', 'introB', 'aboutB1', 'aboutB2', 'aboutB3', 'aboutB4']

Needed Output:

"introA":['aboutA1', 'aboutA2', 'aboutA3', 'aboutA4',],
"introB":['aboutB1', 'aboutB2', 'aboutB3', 'aboutB4',],

>Solution :

Here’s a simple example

wordlist = {}
current_header = None

with open("mydata.txt", "r") as f:
    for line in f:
        line = line.rstrip('\n')

        if not line:
            current_header = None
            continue

        if not current_header:
            current_header = line
            wordlist[current_header] = []

        if current_header != line:
            wordlist[current_header].append(line)

print(wordlist)
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