如何将字符串转换为字典或列表?

如何将字符串转换为字典或列表?

问题描述:

我有以下字符串:

'[1、2、3]'

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

如何将它们转换为列表/字典?

How do I convert them to list/dict?

有人提到 ast.literal_eval eval 可以解析转换为列表/字典的字符串。

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

ast.literal_eval eval 有什么区别?

ast.literal_eval 解析抽象语法树。您几乎在那里拥有json,可以使用该json json.loads ,但您需要双引号而不是单引号才能使字典键有效。

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

此外,这没有评估的风险,因为它不涉及功能评估业务。 eval( subprocess.call(['sudo','rm','-rf','/'])))可以删除您的根目录,但是 ast.literal_eval( subprocess.call(['sudo','rm','-rf','/']))可以预期地失败,并且文件系统完好无损。

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.