python - Convert a String representation of a Dictionary to a dictionary? -


how can convert str representation of dict, such following string, dict?

s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" 

i prefer not use eval. else can use?

the main reason this, 1 of coworkers classes wrote, converts input strings. i'm not in mood go , modify classes, deal issue.

starting in python 2.6 can use built-in ast.literal_eval:

>>> import ast >>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}") {'muffin': 'lolz', 'foo': 'kitty'} 

this safer using eval. own docs say:

 >>> help(ast.literal_eval) on function literal_eval in module ast:  literal_eval(node_or_string)     safely evaluate expression node or string containing python     expression.  string or node provided may consist of following     python literal structures: strings, numbers, tuples, lists, dicts, booleans,     , none. 

for example:

>>> 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 rmtree     onerror(os.listdir, path, sys.exc_info())   file "/opt/python-2.6.1/lib/python2.6/shutil.py", line 206, in rmtree     names = 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_eval     return _convert(node_or_string)   file "/opt/python-2.6.1/lib/python2.6/ast.py", line 67, in _convert     raise valueerror('malformed string') valueerror: malformed string 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -