将字符串转换为dict? [英] Converting string to dict?

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

问题描述

我有一个脚本将一个dict更改为一个字符串并将其保存到一个文件中。我想要加载该文件并将其用作dict,但它是一个字符串。有什么像 int(7),可以更改格式为dict的字符串( {a:1,b:2} )转换成dict?我尝试过 dict(),但这似乎并不是它所做的。我听说过一些涉及JSON和 eval()的过程,但是我看不到这样做。程序加载它保存的相同的数据,如果有人编辑它并且它不起作用,这是没有问题的(我不需要任何高级方法来确认dict数据或任何东西)。

I have a script that changes a dict to a string and saves it to a file. I'd like to then load that file and use it as a dict, but it's a string. Is there something like int("7") that can change a string formatted as a dict ({a: 1, b: 2}) into a dict? I've tried dict(), but this doesn't seem to be what it does. I've heard of some process involving JSON and eval(), but I don't really see what this does. The program loads the same data it saves, and if someone edits it and it doesn't work, it's no problem of mine (I don't need any advanced method of confirming the dict data or anything).

推荐答案

尝试这样做,这是最安全的方式:

Try this, it's the safest way:

import ast
ast.literal_eval("{'x':1, 'y':2}")
=> {'y': 2, 'x': 1}

所有基于 eval()是危险的,恶意代码可以注入字符串内并被执行。

All the solutions based in eval() are dangerous, malicious code could be injected inside the string and get executed.

根据文档表达式得到安全评估。另外,根据源代码 literal_eval 将字符串解析为一个python AST(源代码树),只有当它是文字时才返回。代码永远不会被执行,只能被解析,所以没有理由成为安全风险。

According to the documentation the expression gets evaluated safely. Also, according to the source code, literal_eval parses the string to a python AST (source tree), and returns only if it is a literal. The code is never executed, only parsed, so there is no reason for it to be a security risk.

这篇关于将字符串转换为dict?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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