best way to create a dict from string

T

Tim Arnold

Hi,
I've got some text to parse that looks like this

text = ''' blah blah blah
\Template[Name=RAD,LMRB=False,LMRG=True]{tables}
ho dee ho
'''
I want to extract the bit between the brackets and create a dictionary.
Here's what I'm doing now:

def options(text):
d = dict()
options = text[text.find('[')+1:text.find(']')]
for k,v in [val.split('=') for val in options.split(',')]:
d[k] = v
return d

if __name__ == '__main__':
for line in text.split('\n'):
if line.startswith('\\Template'):
print options(line)


is that the best way or maybe there's something simpler? The options will
always be key=value format, comma separated.
thanks,
--TIm
 
M

MRAB

Tim said:
Hi,
I've got some text to parse that looks like this

text = ''' blah blah blah
\Template[Name=RAD,LMRB=False,LMRG=True]{tables}
ho dee ho
'''

If you're going to include backslashes in the string literal then use a
raw string for safety.
I want to extract the bit between the brackets and create a dictionary.
Here's what I'm doing now:

def options(text):
d = dict()
options = text[text.find('[')+1:text.find(']')]
for k,v in [val.split('=') for val in options.split(',')]:
d[k] = v
return d
1. I'd check whether there's actually a template.

2. 'dict' will accept a list of key/value pairs.

def options(text):
start = text.find('[')
end = text.find(']', start)
if start == -1 or end == -1:
return {}
options = text[start + 1 : end]
return dict(val.split('=') for val in options.split(','))
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top