将字典的字符串表示形式转换为字典?

如何将dictstr表示形式(例如如下字符串)转换为dicthtml

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

我更喜欢不使用eval 。 我还能使用什么? python

形成这种状况的主要缘由是他写的个人同事课程之一,将全部输入都转换为字符串。 我不打算去修改他的课程,以解决这个问题。 json


#1楼

http://docs.python.org/2/library/json.html spa

JSON能够解决此问题,尽管其解码器但愿在键和值周围使用双引号。 若是您不介意更换骇客... code

import json
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
json_acceptable_string = s.replace("'", "\"")
d = json.loads(json_acceptable_string)
# d = {u'muffin': u'lolz', u'foo': u'kitty'}

请注意,若是将单引号做为键或值的一部分,则因为字符替换不当而致使此操做失败。 仅当您对评估解决方案强烈反对时,才建议使用此解决方案。 server

有关JSON单引号的更多信息: JSON响应中的jQuery单引号 htm


#2楼

使用json.loadsip

>>> import json
>>> h = '{"foo":"bar", "foo2":"bar2"}'
>>> d = json.loads(h)
>>> d
{u'foo': u'bar', u'foo2': u'bar2'}
>>> type(d)
<type 'dict'>

#3楼

使用jsonast库消耗大量内存,而且速度较慢。 我有一个过程须要读取156Mb的文本文件。 Ast ,用5分钟延时的转换字典json和用60%更少存储器1分钟! 内存


#4楼

以OP为例: ci

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

咱们能够使用Yaml处理字符串中的这种非标准json:

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

#5楼

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
相关文章
相关标签/搜索