Convert a String representation of a Dictionary to a dictionary?

前端 未结 9 986
醉酒成梦
醉酒成梦 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:33

    To OP's example:

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

    We can use Yaml to deal with this kind of non-standard json in string:

    >>> import yaml
    >>> s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
    >>> s
    "{'muffin' : 'lolz', 'foo' : 'kitty'}"
    >>> yaml.load(s)
    {'muffin': 'lolz', 'foo': 'kitty'}
    

提交回复
热议问题