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}")
asserttype(result) isdict
result = ast.literal_eval("[1, 2, 3]")
asserttype(result) islist
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:
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.
Solution 4:
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 5:
You can eval()
but only with safe data. Otherwise, if you parse unsafe data, take a look into safer ast.literal_eval()
.
JSON parser is also a possibility, most of python dicts and lists have the same syntax.
Post a Comment for "How Can I Convert String To Dict Or List?"