如何从字典中删除不必要的双引号

2024-04-28 12:08:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下字典,我需要删除字典对象中键和值周围不必要的双引号:

d={" 'John'": "'car': 2, 'laptop': 4, 'comp': 3"," 'Jim'": "'car':2, 'laptop':3 ,'computer':2"}

我希望dictionary对象像:

^{pr2}$

以下是我尝试过但出现错误的代码:

ast.literal_eval(d.replace('""', '"'))

最初我有一个string对象,我试图把它解析成dict,我得到了上面的初始d={},所以当我尝试这样做时

print(d['john'])   gives error

但是当我做d[“john'”时,它会打印出正确的值。所以我试着修复它


Tags: 对象代码dictionary字典错误astjohncar
2条回答

假设来源是可信的:

d2 = {eval(k):v for k, v in d.iteritems()}

你想把它转换成dict的dict? 您可以尝试以下代码:

d={" 'John'": "'car': 2, 'laptop': 4, 'comp': 3"," 'Jim'": "'car':2, 'laptop':3 ,'computer':2"}
new_d = {}
for x in d: #x will be 'John' and 'Jim', notice the single quotes will be remained because it's part of the string while double quotes removed as the mark of string
    code = 'new_d['+x+']={'+d[x]+'}' # new_d['John']={'car': 2, 'laptop': 4, 'comp': 3}
    exec code # This means execute string code as python expression
print new_d

相关问题 更多 >