将字典的字符串表示形式转换为字典? [英] Convert a String representation of a Dictionary to a dictionary?
本文介绍了将字典的字符串表示形式转换为字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将 dict
的 str
表示(例如以下字符串)转换为 dict
?
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
我不喜欢使用 eval
.我还能用什么?
造成这种情况的主要原因,是他写的我同事的一个类,将所有输入转换为字符串.我没心情去修改他的课程来处理这个问题.
解决方案
您可以使用内置的 ast.literal_eval
:
这比使用 eval
更安全.正如它自己的文档所说:
例如:
<预><代码>>>>eval("shutil.rmtree('mongo')")回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中.文件<string>",第 1 行,在 <module> 中.文件/opt/Python-2.6.1/lib/python2.6/shutil.py",第 208 行,在 rmtreeonerror(os.listdir, path, sys.exc_info())文件/opt/Python-2.6.1/lib/python2.6/shutil.py",第 206 行,在 rmtree 中名称 = os.listdir(path)OSError: [Errno 2] 没有这样的文件或目录:'mongo'>>>ast.literal_eval("shutil.rmtree('mongo')")回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中.文件/opt/Python-2.6.1/lib/python2.6/ast.py",第 68 行,在literal_eval返回_convert(node_or_string)文件/opt/Python-2.6.1/lib/python2.6/ast.py",第 67 行,在 _convert引发 ValueError('格式错误的字符串')值错误:格式错误的字符串How can I convert the str
representation of a dict
, such as the following string, into a dict
?
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
I prefer not to use eval
. What else can I use?
The main reason for this, is one of my coworkers classes he wrote, converts all input into strings. I'm not in the mood to go and modify his classes, to deal with this issue.
解决方案
You can use the built-in ast.literal_eval
:
>>> import ast
>>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
{'muffin': 'lolz', 'foo': 'kitty'}
This is safer than using eval
. As its own docs say:
>>> help(ast.literal_eval) Help on function literal_eval in module ast: literal_eval(node_or_string) Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
For example:
>>> eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 208, in rmtree
onerror(os.listdir, path, sys.exc_info())
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 206, in rmtree
names = os.listdir(path)
OSError: [Errno 2] No such file or directory: 'mongo'
>>> ast.literal_eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval
return _convert(node_or_string)
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert
raise ValueError('malformed string')
ValueError: malformed string
这篇关于将字典的字符串表示形式转换为字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文