How can I convert string to dict or list?
Solution 1
ast.literal_eval
parses 'abstract syntax trees.' You nearly have json there, for which you could use json.loads
, but you need double quotes, not single quotes, for dictionary keys to be valid.
import ast
result = ast.literal_eval("{'a': 1, 'b': 2}")
assert type(result) is dict
result = ast.literal_eval("[1, 2, 3]")
assert type(result) is list
As a plus, this has none of the risk of eval
, because it doesn't get into the business of evaluating functions. eval("subprocess.call(['sudo', 'rm', '-rf', '/'])")
could remove your root directory, but ast.literal_eval("subprocess.call(['sudo', 'rm', '-rf', '/'])")
fails predictably, with your file system intact.
Solution 2
Use the eval function:
l = eval('[1, 2, 3]')
d = eval("{'a':1, 'b': 2}")
Just make sure you know where these strings came from and that you aren't allowing user input to be evaluated and do something malicious.
Solution 3
python script to convert this string to dict : -
import json
inp_string = '{"1":"one", "2":"two"}'
out = json.loads(inp_string)
print out["1"]
O/P is like :
"one"
Solution 4
You can convert string to list/dict by ast.literal_eval()
or eval()
function. ast.literal_eval()
only considers a small subset of Python's syntax to be valid:
The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
Passing __import__('os').system('rm -rf /')
into ast.literal_eval()
will raise an error, but eval()
will happily wipe your drive.
Since it looks like you're only letting the user input a plain dictionary, use ast.literal_eval()
. It safely does what you want and nothing more.
Admin
Updated on March 08, 2020Comments
-
Admin about 4 years
I have strings such as:
'[1, 2, 3]'
and
"{'a': 1, 'b': 2}"
How do I convert them to list/dict?
Someone mentions that
ast.literal_eval
oreval
can parse a string that converts to list/dict.What's the difference between
ast.literal_eval
andeval
?