簡體   English   中英

如何從字典中刪除不必要的雙引號

[英]how to remove unnecessary double quote from dictionary

我有以下字典,我需要刪除字典對象中鍵和值周圍不必要的雙引號:

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

但是當我做 d["'john'"] 它打印正確的值。 所以我試圖修復它

你想把它轉換成字典的字典嗎? 你可以試試這個代碼:

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

假設來源是可信的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM