2014-02-27 60 views
0

我有一個Python腳本,它從具有多個key=value元素的文件中讀取字符串。一個例子是:Python - 將鍵值字符串轉換爲字典

A=Astring,B=Bstring,C=Cstring 

有沒有一種簡單的方法可以直接讀到字典中?或者,我必須在分割,以及再次分割=後手動創建詞典。

+2

您是否需要處理特殊情況'A =「hello,2 + 2 == 4」,B = potato' – wim

回答

4

拆分與發電機表達和dict()功能:

d = dict(entry.split('=') for entry in inputstring.split(',')) 

演示:

>>> inputstring = 'A=Astring,B=Bstring,C=Cstring' 
>>> dict(entry.split('=') for entry in inputstring.split(',')) 
{'A': 'Astring', 'C': 'Cstring', 'B': 'Bstring'} 
+0

正是我需要的。日Thnx! – Brett

3

你可以簡單地拆分基於,第一,然後您可以拆分根據=每一個項目,像這樣

data = "A=Astring,B=Bstring,C=Cstring" 
print dict(i.split("=") for i in data.split(",")) 
# {'A': 'Astring', 'C': 'Cstring', 'B': 'Bstring'} 
+0

將'list'傳遞給發生器的'dict'函數會有性能優勢,就像'.join'方法一樣的字符串?我問你是因爲「如果字符串更長......」的評論。 – SethMMorton

+0

@SethMMorton是的。請檢查這個[答案](http://stackoverflow.com/a/9061024/1903116) – thefourtheye

+1

@thefourtheye:不,這不是塞思所要求的。該答案顯示了* exception *,其中具有列表理解的'str.join()'比生成器表達式更快。 **這不是這種例外**。 –

相關問題