Home > database >  I am trying to write a code in python to get the values from a multiline string and store it in dict
I am trying to write a code in python to get the values from a multiline string and store it in dict

Time:11-11

enter image description here

CodePudding user response:

you can use this code:

# 
import re


description = '''add DL3,DL1,DL5,DL6
id7
add DL2, DL3, DL4
id1
id2
id3
add DL3
id1
id2
id3
'''


action = []
item = {}
for line in description.splitlines(): 
    if re.search(r'^add', line):
        if item:
            action.append(item)
            item = {}        
        process, dll = line.split(' ', 1)
        item['process'] = process
        item['dl_names'] = [dl.strip() for dl in dll.split(',')]
        item['id']=[]
    else:
        item['id'].append(line.strip())
if item:
    action.append(item)        

print(action)
  • Related