Python convert string object into dictionary

前端 未结 4 1372
太阳男子
太阳男子 2021-01-14 21:48

I have been working to build a complex data structure which would return a dictionary. Currently that class return string object of the form

{
   cset : x,           


        
4条回答
  •  [愿得一人]
    2021-01-14 22:15

    Don't use eval. If you are sure that the string will always contain a valid Python dict, use ast.literal_eval. This works pretty much like eval, but it only evaluates if the expression is a valid dict,list, etc. and throws an exceptions if it isn't. This is way safer than trying to evaluate strings that may contain arbitrary code at runtime.

    From the docs:

    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.

    This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

    Code Example:

    >>> import ast
    >>> ast.literal_eval("1+1")
    Traceback (most recent call last):
      File "", line 1, in 
      File "/usr/lib/python2.6/ast.py", line 68, in literal_eval
        return _convert(node_or_string)
      File "/usr/lib/python2.6/ast.py", line 67, in _convert
        raise ValueError('malformed string')
    ValueError: malformed string
    >>> ast.literal_eval("\"1+1\"")
    '1+1'
    >>> ast.literal_eval("{'a': 2, 'b': 3, 3:'xyz'}")
    {'a': 2, 3: 'xyz', 'b': 3}
    

提交回复
热议问题