在Python中將列表字串轉換為字典


這裡我們有這樣一種情況:如果一個字串包含的元素使其成為一個列表,但這些元素也可以表示一個鍵值對,使其成為一個字典。在本文中,我們將展示如何使用這樣的列表字串並將其變成一個字典。

使用 split 和 slicing

在此方法中,我們使用 split 函式將元素分隔為鍵值對,並使用切片將鍵值對轉換為字典格式。

示例

 即時演示

stringA = '[Mon:3, Tue:5, Fri:11]'
# Given string
print("Given string : \n",stringA)
# Type check
print(type(stringA))
# using split
res = {sub.split(":")[0]: sub.split(":")[1] for sub in stringA[1:-1].split(", ")}
# Result
print("The converted dictionary : \n",res)
# Type check
print(type(res))

輸出

執行以上程式碼,我們得到以下結果 -

('Given string : \n', '[Mon:3, Tue:5, Fri:11]')

('The converted dictionary : \n', {'Fri': '11', 'Mon': '3', 'Tue': '5'})

使用 eval 和 replace

eval 函式可以從字串中獲取實際列表,然後 replace 將每個元素轉換為一個鍵值對。

示例

 即時演示

stringA = '[18:3, 21:5, 34:11]'
# Given string
print("Given string : \n",stringA)
# Type check
print(type(stringA))
# using eval
res = eval(stringA.replace("[", "{").replace("]", "}"))
# Result
print("The converted dictionary : \n",res)
# Type check
print(type(res))

輸出

執行以上程式碼,我們得到以下結果 -

('Given string : \n', '[18:3, 21:5, 34:11]')

('The converted dictionary : \n', {18: 3, 34: 11, 21: 5})

更新日期:2020-06-04

930 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告