I have a string like
s = "title='bah' name='john and jill' purple='haze' none=None i=1"
I am looking for a pythonic way of putting that into a dictionary (and a solution that does not choke on extra white spaces)?
Suggestions ?
>>> from ast import literal_eval
>>> s = "title='bah' name='john' purple='haze' none=None i=1"
>>> dict((k, literal_eval(v)) for k, v in (pair.split('=') for pair in s.split()))
{'purple': 'haze', 'i': 1, 'none': None, 'name': 'john', 'title': 'bah'}
(This won't work if the inner strings contain whitespace, or if '='
appears as anything other than the key-value separator. Obviously the more complicated this gets the harder it is to parse, so...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With