将字典的字符串表示转换为字典?

  • 问题:
  • 如何将dictstr表示转换为dict?在

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

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

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

  • 答案:
  • 从Python2.6开始,您可以使用内置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.

    例如:

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