TheRimalaya TheRimalaya - 1 month ago 6
Python Question

Plain list with heading in between into dictionary in python

I have a situation like below:

Heading 1
item 1
item 2
Heading 2
item 1
Heading 3
item 1
item 2
item 3


This is a plain list of text, I need to convert this into a dictionary in python as,

{
Heading 1: [item 1, item 2],
Heading 2: [item 1],
Heading 3: [item 1, item 2, item 3]
}


Any item to achieve this? I am working with python and pandas specially.

Answer
dictionary = {}
for line in open('text.file'):
    if line.split()[0] == "Heading": 
        current = line
        dictionary[line] = []
        continue
    dictionary[current].append(line)

This will fail if the first line in the file isn't a heading, but you expect this is so that's good. You save the current heading, and continue to append the items to the current cell in the dict.