如何将字符串转换为字典或列表? [英] How can I convert string to dict or list?
问题描述
我有以下字符串:
'[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.
这篇关于如何将字符串转换为字典或列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!