2011-01-21 33 views
9

我有串如下:從空間創建字典分隔的key = value字符串在Python

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

我想在轉換爲字典如下:

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

如何做到這一點在Python中?

+0

應該發生什麼,如果你的字符串是''鍵1 =‘’富‘欄鍵2 =’baz'`? – 2011-01-21 22:50:28

+0

我解析日誌文件的輸出,我不希望以任何其他格式輸出。 – 2011-01-24 16:00:20

回答

15

試試這個:

>>> 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)} 
18

shlex類可以很容易地編寫簡單的語法 一如當年的 詞法分析器Unix shell。 這對於編寫 小語言(例如,運行 Python應用程序的控制文件) 或解析帶引號的字符串通常很有用。

import shlex 

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

print dict(token.split('=') for token in shlex.split(s)) 
相關問題