2014-07-18 131 views
1

我有這樣的字符串:如何在python中將特殊字符串映射爲字典?

a_1 = 'A=1,B=3,C=3' 

我要地圖這個字符串到dict的樣子:

d_1 = {'A':1,'B':2,'C':3} 

我應該怎麼辦呢?我使用:

dict(a_1) 

但這返回一個錯誤:

ValueError: dictionary update sequence element #0 has length 1; 2 is required. 

回答

5

可以使用split()加上一個修真做到這一點:

d_1 = dict(pair.split("=") for pair in a_1.split(",")) 
+0

+1實際上它是 「近乎完美」 導致你的地圖創建'{ 'A': '1',...}'他希望vals是整數:'{'A':1,...}' – alfasin

+0

非常棒的解決方案。非常感謝! –

+0

@ alfasin,這很好,因爲我的字符串中的某些值也是一個「字符串」。 :) –

2

強迫到int

>>> s = 'A=1,B=3,C=3' 
>>> dict((k, int(v)) for k, v in [x.split("=") for x in s.split(",")]) 
{'A': 1, 'C': 3, 'B': 3} 

更新:試圖強迫值int一個版本:

def maybeint(s): 
    try: 
     return int(s) 
    except ValueError: 
     return s 

s = 'A=1,B=3,C=3,D=a' 
d = dict((k, maybeint(v)) for k, v in [x.split("=") for x in s.split(",")])