>>> help(ast.literal_eval)Help on function literal_eval in module ast:
literal_eval(node_or_string)Safely evaluate an expression node or a string containing a Pythonexpression. The string or node provided may only consist of the followingPython literal structures: strings, numbers, tuples, lists, dicts, booleans,and None.
例如:
>>> eval("shutil.rmtree('mongo')")Traceback (most recent call last):File "<stdin>", line 1, in <module>File "<string>", line 1, in <module>File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 208, in rmtreeonerror(os.listdir, path, sys.exc_info())File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 206, in rmtreenames = os.listdir(path)OSError: [Errno 2] No such file or directory: 'mongo'>>> ast.literal_eval("shutil.rmtree('mongo')")Traceback (most recent call last):File "<stdin>", line 1, in <module>File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_evalreturn _convert(node_or_string)File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convertraise ValueError('malformed string')ValueError: malformed string
string = "{'server1':'value','server2':'value'}"
#Now removing { and }s = string.replace("{" ,"")finalstring = s.replace("}" , "")
#Splitting the string based on , we get key value pairslist = finalstring.split(",")
dictionary ={}for i in list:#Get Key Value pairs separately to store in dictionarykeyvalue = i.split(":")
#Replacing the single quotes in the leading.m= keyvalue[0].strip('\'')m = m.replace("\"", "")dictionary[m] = keyvalue[1].strip('"\'')
print dictionary
s = s.replace("{", "").replace("}", "").split(",")
dictionary = {}
for i in s:dictionary[i.split(":")[0].strip('\'').replace("\"", "")] = i.split(":")[1].strip('"\'')
print(dictionary)