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

时间:2011-01-21 22:34:41

标签: python dictionary

我的字符串如下:

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

我想按如下方式转换为字典:

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

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

2 个答案:

答案 0 :(得分:24)

  

shlex类使编写变得容易   用于简单语法的词法分析器   类似于Unix shell。   这通常对写作很有用   minilanguages,(例如,在奔跑中   Python应用程序的控制文件)   或者用于解析引用的字符串。

import shlex

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

print dict(token.split('=') for token in shlex.split(s))

答案 1 :(得分:16)

试试这个:

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

如果您还想删除引号:

>>> {k:v.strip('"') for k,v in re.findall(r'(\S+)=(".*?"|\S+)', s)}
相关问题