在Python中用空格分隔key = value字符串创建字典

Hem*_*hah 12 python dictionary

我有如下字符串:

s = 'key1=1234 key2="string with space" key3="SrtingWithoutSpace"'
Run Code Online (Sandbox Code Playgroud)

我想转换成字典如下:

key  | value
-----|--------  
key1 | 1234
key2 | string with space
key3 | SrtingWithoutSpace

我如何在Python中执行此操作?

Joc*_*zel 26

shlex类可以很容易地编写简单的语法类似的Unix外壳的词法分析器.这对于编写小语言(例如,在Python应用程序的运行控制文件中)或解析引用的字符串通常很有用.

import shlex

s = 'key1=1234 key2="string with space" key3="SrtingWithoutSpace"'

print dict(token.split('=') for token in shlex.split(s))
Run Code Online (Sandbox Code Playgroud)

  • `dict(token.split('=', 1)`,否则如果值中有`=`会发生什么? (3认同)

Mar*_*ers 17

试试这个:

>>> import re
>>> dict(re.findall(r'(\S+)=(".*?"|\S+)', s))
{'key3': '"SrtingWithoutSpace"', 'key2': '"string with space"', 'key1': '1234'}
Run Code Online (Sandbox Code Playgroud)

如果您还想删除引号:

>>> {k:v.strip('"') for k,v in re.findall(r'(\S+)=(".*?"|\S+)', s)}
Run Code Online (Sandbox Code Playgroud)