[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

best way to create a dict from string

Tim Arnold

2/18/2010 4:21:00 PM

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


1 Answer

MRAB

2/19/2010 5:50:00 PM

0

Tim Arnold wrote:
> 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(','))

> 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,
>