如何將dict
的str
表示形式(例如如下字符串)轉換爲dict
? html
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
我更喜歡不使用eval
。 我還能使用什麼? python
形成這種狀況的主要緣由是他寫的個人同事課程之一,將全部輸入都轉換爲字符串。 我不打算去修改他的課程,以解決這個問題。 json
http://docs.python.org/2/library/json.html spa
JSON能夠解決此問題,儘管其解碼器但願在鍵和值周圍使用雙引號。 若是您不介意更換駭客... code
import json s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" json_acceptable_string = s.replace("'", "\"") d = json.loads(json_acceptable_string) # d = {u'muffin': u'lolz', u'foo': u'kitty'}
請注意,若是將單引號做爲鍵或值的一部分,則因爲字符替換不當而致使此操做失敗。 僅當您對評估解決方案強烈反對時,才建議使用此解決方案。 server
有關JSON單引號的更多信息: JSON響應中的jQuery單引號 htm
使用json.loads
: ip
>>> import json >>> h = '{"foo":"bar", "foo2":"bar2"}' >>> d = json.loads(h) >>> d {u'foo': u'bar', u'foo2': u'bar2'} >>> type(d) <type 'dict'>
使用json
。 ast
庫消耗大量內存,而且速度較慢。 我有一個過程須要讀取156Mb的文本文件。 Ast
,用5分鐘延時的轉換字典json
和用60%更少存儲器1分鐘! 內存
以OP爲例: ci
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
咱們能夠使用Yaml處理字符串中的這種非標準json:
>>> import yaml >>> s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" >>> s "{'muffin' : 'lolz', 'foo' : 'kitty'}" >>> yaml.load(s) {'muffin': 'lolz', 'foo': 'kitty'}
string = "{'server1':'value','server2':'value'}" #Now removing { and } s = string.replace("{" ,"") finalstring = s.replace("}" , "") #Splitting the string based on , we get key value pairs list = finalstring.split(",") dictionary ={} for i in list: #Get Key Value pairs separately to store in dictionary keyvalue = i.split(":") #Replacing the single quotes in the leading. m= keyvalue[0].strip('\'') m = m.replace("\"", "") dictionary[m] = keyvalue[1].strip('"\'') print dictionary