简体   繁体   中英

How can I convert string to dict or list?

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 or eval can parse a string that converts to list/dict.

What's the difference between ast.literal_eval and eval ?

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.

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.

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.

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"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM