如何将字符串转换为字典或列表? [英] How can I convert string to dict or list?

查看:737
本文介绍了如何将字符串转换为字典或列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字符串:

'[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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆