How can I parse this form with python

412 views python


NAME: amiee AGE: 10 SHCOOL: elementary school

this is really long form, maybe there are more than 10 subjects. How can I parse this sentence easily without split...? I wanna save this form to dictionary, like.

{amiee:{AGE:10, SCHOOL: elementary school ... }}

answered question

Show your own effort and code to solve the problem (as properly formatted text in the question)

Why do you want to parse it "without split"?

1 Answer


You can use re.findall to extract a list of key-value pairs from the input string, use it to create an intermediate dict, then get the name and delete it from the dict, and create a new dict with the name and what's left in the intermediate dict:

import re
form = 'NAME: amiee AGE: 10 SHCOOL: elementary school'
d = dict(re.findall(r'([A-Z]+): (.*?)(?=\s*[A-Z]+: |$)', form))
name = d['NAME']
del d['NAME']
print({name: d})

This outputs:

{'amiee': {'AGE': '10', 'SHCOOL': 'elementary school'}}

posted this

Have an answer?


Please login first before posting an answer.