parse a string of parameters and values
Peter Otten
__peter__ at web.de
Sun Dec 13 05:28:24 EST 2009
bsneddon wrote:
> I have a problem that I can come up with a brute force solution to
> solve but it occurred to me that there may be an
> "one-- and preferably only one --obvious way to do it".
>
> I am going to read a text file that is an export from a control
> system.
> It has lines with information like
>
> base=1 name="first one" color=blue
>
> I would like to put this info into a dictionary for processing.
> I have looked at optparse and getopt maybe they are the answer but
> there could
> be and very straight forward way to do this task.
>
> Thanks for your help
Have a look at shlex:
>>> import shlex
>>> s = 'base=1 name="first one" color=blue equal="alpha=beta" empty'
>>> dict(t.partition("=")[::2] for t in shlex.split(s))
{'color': 'blue', 'base': '1', 'name': 'first one', 'empty': '', 'equal':
'alpha=beta'}
Peter
More information about the Python-list
mailing list