我有以下字典,我需要删除字典对象中的键和值周围不必要的双引号:
d={" 'John'": "'car': 2, 'laptop': 4, 'comp': 3"," 'Jim'": "'car':2, 'laptop':3 ,'computer':2"}
我希望字典对象像:
d={'John': 'car': 2, 'laptop': 4, 'comp': 3,'Jim':'car':2, 'laptop':3 ,'computer':2}
这是我尝试的代码,但却出错:
ast.literal_eval(d.replace('""', '"'))
最初我有一个字符串对象,我试图解析为dict,我得到了上面的初始d = {}所以当我尝试做
print(d['john']) gives error
但是当我做["' john'"]时,它会输出正确的值。所以我试图修理它
答案 0 :(得分:0)
你想将它转换为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
答案 1 :(得分:0)
假设源是可信的:
d2 = {eval(k):v for k, v in d.iteritems()}