Convert a String representation of a Dictionary to a dictionary?

前端 未结 9 983
醉酒成梦
醉酒成梦 2020-11-21 05:22

How can I convert the str representation of a dict, such as the following string, into a dict?

s = \"{\'muffin\' : \'l         


        
相关标签:
9条回答
  • 2020-11-21 05:44

    using json.loads:

    >>> import json
    >>> h = '{"foo":"bar", "foo2":"bar2"}'
    >>> d = json.loads(h)
    >>> d
    {u'foo': u'bar', u'foo2': u'bar2'}
    >>> type(d)
    <type 'dict'>
    
    0 讨论(0)
  • 2020-11-21 05:45

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

    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
    
    0 讨论(0)
  • 2020-11-21 05:46

    no any libs are used:

    dict_format_string = "{'1':'one', '2' : 'two'}"
    d = {}
    elems  = filter(str.isalnum,dict_format_string.split("'"))
    values = elems[1::2]
    keys   = elems[0::2]
    d.update(zip(keys,values))
    

    NOTE: As it has hardcoded split("'") will work only for strings where data is "single quoted".

    0 讨论(0)
提交回复
热议问题