best way to create a dict from string

MRAB python at mrabarnett.plus.com
Fri Feb 19 18:50:19 CET 2010


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




More information about the Python-list mailing list