help with creating dict from string

Peter Otten __peter__ at web.de
Thu Nov 6 12:40:44 EST 2014


Tim wrote:

> hi, I have strings coming in with this format:
> 
>     '[one=two, three=four five, six, seven=eight]'
> 
> and I want to create from that string, this dictionary:
>     {'one':'two', 'three':'four five', 'six':True, 'seven':'eight'}
> 
> These are option strings, with each key-value pair separated by commas.
> Where there is a value, the key-value pair is separated by '='.
> 
> This is how I started (where s is the string):
>     s = s.replace('[','').replace(']','')
>     s = [x.split('=') for x in s.split(',')]
> 
>     [['one', 'two'], [' three', 'four five'], [' six'], [' seven',
>     [['eight']]
> 
> I know I can iterate and strip each item, fixing single-element keys as I
> go.
> 
> I just wondered if I'm missing something more elegant. If it wasn't for
> the leading spaces and the boolean key, the dict() constructor would have
> been sweet.

Not everything has to be a one-liner ;) If it works I don't think something

>>> s = '[one=two, three=four five, six, seven=eight]'
>>> def fix(pair):
...     key, eq, value = pair.partition("=")
...     return key.strip(), value if eq else True
... 
>>> dict(fix(t) for t in s.strip("[]").split(","))
{'three': 'four five', 'seven': 'eight', 'one': 'two', 'six': True}

is particularly inelegant. Are you sure that your grammar is not more 
complex than your example, e. g. that "," cannot occur in the values?




More information about the Python-list mailing list