parse a string of parameters and values

bsneddon bsneddon at yahoo.com
Sun Dec 13 10:23:19 EST 2009


On Dec 13, 5:28 am, Peter Otten <__pete... at web.de> wrote:
> 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

Thanks to all for your input.

It seems I miss stated the problem.  Text is always quoted so blue
above -> "blue".

Peter,

The part I was missing was t.partition("=") and slicing skipping by
two.
It looks like a normal split will work for me to get the arguments I
need.
To my way of thinking your is very clean any maybe the "--obvious way
to do it"
Although it was not obvious to me until seeing your post.

Bill



More information about the Python-list mailing list