parse a string of parameters and values

Tim Chase python.list at tim.thechases.com
Mon Dec 14 19:51:06 EST 2009


Gabriel Genellina wrote:
> Peter Otten escribió:
>> bsneddon wrote:
>>> 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.
>>>>> 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'}
> 
> Brilliant!

The thing I appreciated about Peter's solution was learning a 
purpose for .partition() as I've always just used .split(), so I 
would have done something like

 >>> dict('=' in s and s.split('=', 1) or (s, '') for s in 
shlex.split(s))
{'color': 'blue', 'base': '1', 'name': 'first one', 'empty': '', 
'equal': 'alpha=beta'}

Using .partition() makes that a lot cleaner.  However, it looks 
like .partition() was added in 2.5, so for my code stuck in 2.4 
deployments, I'll stick with the uglier .split()

-tkc





More information about the Python-list mailing list