2017-10-28 103 views
1

如何從下列內容中刪除單引號,以便將它識別爲與一個字符串對象列表相同的一個字典對象列表?鑑於它是一個列表,我不能使用pd.replace。從python字典列表中刪除引號

['{"PLAYER":"Player Name","SALARY":"0000.00","OPP":"CI","POS":"BR","TEAM":"IT","SCHEDULE_ID":"40623","PLAYERID":"12322","GP":"5","TAR":"64","RZTAR":"6","POW TAR":"32.99%","WEEK 2":"11","WEEK 3":"14","WEEK 4":"9","WEEK 5":"19","ARDS":"545","YPT":"8.52","REC":"40","REC RATE":"62.50%"}'] 
+0

你不必名單字典;你有一個字符串列表。該字符串看起來是一個JSON值,可以將其解碼爲字典。不過,你需要知道字符串的來源,以確定它是如何被解釋的。 – chepner

+0

我知道我沒有詞典列表。字典列表是我的目標。如何做到這一點是我的問題,@ Ajax1234下面回答。我希望將字符串列表視爲字典。爲了做到這一點,我需要刪除列表中每個可能字典周圍的單引號。 「ast」解決方案完美運作。 – toussaint31

回答

1

您可以使用ast.literal_eval

import ast 
s = ['{"PLAYER":"Player Name","SALARY":"0000.00","OPP":"CI","POS":"BR","TEAM":"IT","SCHEDULE_ID":"40623","PLAYERID":"12322","GP":"5","TAR":"64","RZTAR":"6","POW TAR":"32.99%","WEEK 2":"11","WEEK 3":"14","WEEK 4":"9","WEEK 5":"19","ARDS":"545","YPT":"8.52","REC":"40","REC RATE":"62.50%"}'] 
final_s = [ast.literal_eval(i) for i in s] 

輸出:

[{'SALARY': '0000.00', 'REC RATE': '62.50%', 'OPP': 'CI', 'YPT': '8.52', 'TAR': '64', 'GP': '5', 'PLAYERID': '12322', 'WEEK 3': '14', 'POS': 'BR', 'ARDS': '545', 'WEEK 2': '11', 'PLAYER': 'Player Name', 'SCHEDULE_ID': '40623', 'POW TAR': '32.99%', 'WEEK 4': '9', 'TEAM': 'IT', 'RZTAR': '6', 'REC': '40', 'WEEK 5': '19'}] 
+0

該解決方案完美運作。我能夠輕鬆完成我的下一步,即將(現在)字典的列表變成一個數據框。 – toussaint31

0

只是使用eval()爲宗旨

s=['{"PLAYER":"PlayerName","SALARY":"0000.00","OPP":"CI","POS":"BR","TEAM":"IT","SCHEDULE_ID":"40623","PLAYERID":"12322","GP":"5","TAR":"64","RZTAR":"6","POW TAR":"32.99%","WEEK 2":"11","WEEK 3":"14","WEEK 4":"9","WEEK 5":"19","ARDS":"545","YPT":"8.52","REC":"40","REC RATE":"62.50%"}'] 

s = [eval(item) for item in s]