How to convert a string to dict or list?

I have lines like this:

'[1, 2, 3]'

and

"{'a': 1, 'b': 2}"

How to convert them to a / dict list?

Someone mentions that ast.literal_eval or eval can parse a string that is converted to a / dict list.

What is the difference between ast.literal_eval and eval ?

+5
source share
5 answers

ast.literal_eval parses abstract syntax trees. You almost have json for which you can use json.loads , but you need double quotes, not single quotes, so that the dictionary keys are 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 is not at risk of eval , as it is not part of the function evaluation business. eval("subprocess.call(['sudo', 'rm', '-rf', '/'])") can delete your root directory, but ast.literal_eval("subprocess.call(['sudo', 'rm', '-rf', '/'])") unpredictable, and your file system is not damaged.

+7
source

Use the eval function:

 l = eval('[1, 2, 3]') d = eval("{'a':1, 'b': 2}") 

Just make sure you know where these lines came from, and that you are not allowing the user to enter data or do something malicious.

+3
source

You can convert a string to a / dict list using the function ast.literal_eval() or eval() . ast.literal_eval() only takes into account a small subset of Python syntax:

A given string or node can only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

Passing __import__('os').system('rm -rf /') to ast.literal_eval() will result in an error, but eval() happily erase your disk.

Since it looks like you are allowing the user to enter a simple dictionary, use ast.literal_eval() . He safely does what you want, and nothing more.

+1
source

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 as follows:

 "one" 
+1
source

You can eval() , but only with safe data. Otherwise, if you are analyzing insecure data, check out the safer ast.literal_eval() .

JSON parser is also an option; most pythons and lists have the same syntax.

0
source

All Articles