将字典的字符串表示转换为字典? [英] Convert a String representation of a Dictionary to a dictionary?
本文介绍了将字典的字符串表示转换为字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将 str
表示为 dict
(如下列字符串)转换为 dict
?
How can I convert the str
representation of a dict
, such as the following string, into a dict
?
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
我不想使用 eval
。还有什么我可以使用的?
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.
推荐答案
从Python 2.6开始可以使用内置的 ast.literal_eval
:
Starting in Python 2.6 you can use the built-in ast.literal_eval
:
>>> import ast
>>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
{'muffin': 'lolz', 'foo': 'kitty'}
这比使用 eval
更安全。正如其自己的文档所说:
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.
例如:
>>> 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屋!
查看全文