Convert a String representation of a Dictionary to a dictionary?

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

    string = "{'server1':'value','server2':'value'}"
    
    #Now removing { and }
    s = string.replace("{" ,"")
    finalstring = s.replace("}" , "")
    
    #Splitting the string based on , we get key value pairs
    list = finalstring.split(",")
    
    dictionary ={}
    for i in list:
        #Get Key Value pairs separately to store in dictionary
        keyvalue = i.split(":")
    
        #Replacing the single quotes in the leading.
        m= keyvalue[0].strip('\'')
        m = m.replace("\"", "")
        dictionary[m] = keyvalue[1].strip('"\'')
    
    print dictionary
    

提交回复
热议问题