python – Convert a String representation of a Dictionary to a dictionary?
python – Convert a String representation of a Dictionary to a dictionary?
You can use the built-in ast.literal_eval
:
>>> import ast
>>> ast.literal_eval({muffin : lolz, foo : kitty})
{muffin: lolz, foo: kitty}
This is safer than using eval
. As its own docs say:
>>> 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 Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and 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
https://docs.python.org/3.8/library/json.html
JSON can solve this problem though its decoder wants double quotes around keys and values. If you dont mind a replace hack…
import json
s = {muffin : lolz, foo : kitty}
json_acceptable_string = s.replace(, )
d = json.loads(json_acceptable_string)
# d = {umuffin: ulolz, ufoo: ukitty}
NOTE that if you have single quotes as a part of your keys or values this will fail due to improper character replacement. This solution is only recommended if you have a strong aversion to the eval solution.
More about json single quote: jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON
python – Convert a String representation of a Dictionary to a dictionary?
using json.loads
:
>>> import json
>>> h = {foo:bar, foo2:bar2}
>>> d = json.loads(h)
>>> d
{ufoo: ubar, ufoo2: ubar2}
>>> type(d)
<type dict>