Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string of kwargs to kwargs

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 ?

like image 608
Nix Avatar asked Dec 13 '22 05:12

Nix


1 Answers

>>> 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...)

like image 174
Ismail Badawi Avatar answered Dec 24 '22 16:12

Ismail Badawi