string of kwargs to kwargs

ε祈祈猫儿з 提交于 2019-12-13 13:26:29

问题


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 ?


回答1:


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




回答2:


If you have control over the strings, as you say you do, you could simply do this

>>> s = "title='bah' name='john' purple='haze' none=None i=1"
>>> eval("dict(%s)"%s.replace(" ",","))
{'i': 1, 'purple': 'haze', 'none': None, 'name': 'john', 'title': 'bah'}
>>> 



回答3:


>>> dictionary = {}
>>> for i in s.split():
...     dictionary[i.split('=')[0]] = i.split('=')[1]
...
>>> dictionary
{'purple': "'haze'", 'i': '1', 'none': 'None', 'name': "'john'", 'title': "'bah'"}



回答4:


Looks like @Nix missed the call to split() in previous answer.

Here is the corrected code:

>>> s = "title='bah' name='john' purple='haze' none=None i=1"
>>> d = eval("dict(%s)" % ','.join(s.split()))
>>> d
{'i': 1, 'purple': 'haze', 'none': None, 'name': 'john', 'title': 'bah'}
>>>

The down vote is likely because his original code:

s = "title='bah' name='john' purple='haze' none=None i=1"
d = eval("dict(%s)"% ",".join(s))

produces the following error:

>>> s = "title='bah' name='john' purple='haze' none=None i=1"
>>> d = eval("dict(%s)"% ",".join(s))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    dict(t,i,t,l,e,=,',b,a,h,', ,n,a,m,e,=,',j,o,h,n,', ,p,u,r,p,l,e,=,',h,a,z,e,', ,n,o,n,e,=,N,o,n,e, ,i,=,1)
                   ^
SyntaxError: invalid syntax



回答5:


A combination of @gnibblers and @RanRag that does not barf on whitespace. (e.g. title='foo bar')

s = "title='bah' name='john' purple='haze' none=None i=1"
d = eval("dict(%s)"% ",".join(s.split()))


来源:https://stackoverflow.com/questions/9305387/string-of-kwargs-to-kwargs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!