python - 将字典的字符串表示形式转换为字典

标签 python string dictionary

如何将 dictstr 表示形式(例如以下字符串)转换为 dict

s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"

我不喜欢使用 eval。我还能用什么?

主要原因是他写的我的同事类(class)之一,将所有输入转换为字符串。我没心情去修改他的类(class)来处理这个问题。

最佳答案

您可以使用内置的ast.literal_eval :

>>> import ast
>>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
{'muffin': 'lolz', 'foo': 'kitty'}

这比使用 eval 更安全。正如它自己的文档所说:

>>> 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

关于python - 将字典的字符串表示形式转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/988228/

相关文章:

java - 我如何在通用类中使用 intValue()

C++ 映射值在运行时没有改变,我做错了什么?

python - QUdpSocket pyqt qt

python - 生成使用默认命名空间的 XML

c - char[] 如何表示 UTF-8 字符串?

python 字典到 csv,其中每个键位于单独的行中,值位于单独的列中

ios - 字典是 Xcode 中的假定集合(数组)吗?

python - 多项式系数的最大递归

python - 如何解决ajax代码中FLASK的404错误?

c# - 在不使用 string.Join 的情况下加入 string[]