Python 将字符串转换为字典?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13675942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting string to dict?
提问by tkbx
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).
我有一个脚本,可以将 dict 更改为字符串并将其保存到文件中。我想然后加载该文件并将其用作字典,但它是一个字符串。有没有类似的东西int("7")可以将格式化为 dict ( {a: 1, b: 2})的字符串更改为 dict ?我试过了dict(),但这似乎不是它的作用。我听说过一些涉及 JSON 和 的过程eval(),但我真的不知道这是做什么的。该程序加载它保存的相同数据,如果有人编辑它并且它不起作用,我的没问题(我不需要任何确认dict数据或任何东西的高级方法)。
采纳答案by óscar López
Try this, it's the safest way:
试试这个,这是最安全的方法:
import ast
ast.literal_eval("{'x':1, 'y':2}")
=> {'y': 2, 'x': 1}
All the solutions based in eval()are dangerous, malicious code could be injected inside the string and get executed.
所有基于 in 的解决方案eval()都是危险的,恶意代码可能会被注入到字符串中并被执行。
According to the documentationthe expression gets evaluated safely. Also, according to the source code, literal_evalparses 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.
根据文档,表达式得到安全评估。此外,根据源代码,literal_eval将字符串解析为python AST(源代码树),仅当它是文字时才返回。代码永远不会执行,只会被解析,因此没有理由将其视为安全风险。
回答by Matthew Adams
You can use evalif you trust the input string.
eval如果您信任输入字符串,则可以使用。
>>> a=eval('{"a":1,"b":2}')
>>> a
{'a': 1, 'b': 2}
回答by phihag
回答by Matthew Adams
Serialization
序列化
What you are talking about doing is object serialization, and there are better ways of doing it than rolling your own serialization method (though you seem to have come up with YAML). Both of these are still less secure than the ast.literal_eval()approach (pickleparticularly), but they definitely should be noted here.
您正在谈论的是object serialization,并且有比滚动您自己的序列化方法更好的方法(尽管您似乎已经提出了 YAML)。这两种方法仍然不如方法安全ast.literal_eval()(pickle特别是),但在这里绝对应该注意它们。
JSON
JSON
Here is an example of doing what you want using JSON, a popular cross-language format:
以下是使用JSON(一种流行的跨语言格式)做您想做的事的示例:
import json
myDict = {'a':1, 'b':2}
# write to the file 'data'
with open('data','w') as f:
json.dump(myDict, f)
# now we can load it back
with open('data','r') as f:
myDictLoaded = json.load(f)
print myDictLoaded
Output:
输出:
{u'a': 1, u'b': 2}
pickle
泡菜
Here is a second example doing the same thing using pickle. pickleis more powerful in that it can serialize all* python objects, even ones you write.
这是使用pickle做同样事情的第二个例子。pickle更强大的是它可以序列化所有* python 对象,甚至是您编写的对象。
import cPickle as pickle
myDict = {'a':1, 'b':2}
# write to the file 'data'
with open('data','w') as f:
pickle.dump(myDict, f)
# now we can load it back
with open('data','r') as f:
myDictLoaded = pickle.load(f)
print myDictLoaded
Output:
输出:
{'a': 1, 'b': 2}

