ast*_*rog 6 python string dictionary
将一串keyword =值转换为字典的最简单方法是什么,例如以下字符串:
name="John Smith", age=34, height=173.2, location="US", avatar=":,=)"
Run Code Online (Sandbox Code Playgroud)
到下面的python字典:
{'name':'John Smith', 'age':34, 'height':173.2, 'location':'US', 'avatar':':,=)'}
Run Code Online (Sandbox Code Playgroud)
'avatar'键只是为了表明字符串可以包含=和,所以简单的'拆分'是不行的.有任何想法吗?谢谢!
这对我有用:
# get all the items
matches = re.findall(r'\w+=".+?"', s) + re.findall(r'\w+=[\d.]+',s)
# partition each match at '='
matches = [m.group().split('=', 1) for m in matches]
# use results to make a dict
d = dict(matches)
Run Code Online (Sandbox Code Playgroud)