Convert a String representation of a Dictionary to a dictionary?

前端 未结 9 951
醉酒成梦
醉酒成梦 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: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".

提交回复
热议问题