best way to create a dict from string

Tim Arnold tim.arnold at sas.com
Thu Feb 18 17:20:44 CET 2010


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





More information about the Python-list mailing list