簡體   English   中英

如何將字符串從列表轉換為字典?

[英]How to convert a string to a dict from a list?

我嘗試了幾種方法將類似字典的 str 從列表轉換為字典,但無法弄清楚如何正確解釋錯誤消息。

我有一個清單:

list = [(45, "{'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': None, 'family': None}"), (12383, "{'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': 'Fagales', 'family': None}"), (12384, "{'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': 'Primulales', 'family': None}"), (12385, "{'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': 'Magnoliales', 'family': None}"), (12386, "{'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': 'Celastrales', 'family': None}")]

並想將類似字典的字符串轉換為字典,這樣我就可以按鍵訪問這些值。 我努力了:

test = (list[0][1]).replace("'", "\"")
dict(test)

但得到以下錯誤:

ValueError: dictionary update sequence element #0 has length 1; 2 is required

我也試過 json.loads()

test2 = json.loads(test)

返回:

JSONDecodeError: Expecting value: line 1 column 34 (char 33)

當我在 dict() 函數中手動插入字符串時,字符串成功轉換為 dict 但在使用列表索引時沒有。 如果有人能解釋為什么存在這種差異以及如何將字符串直接轉換為字典,我將不勝感激。

謝謝你的幫助

您可以使用ast.literal_eval

from ast import literal_eval

lst = [(45, "{'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': None, 'family': None}"), (12383, "{'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': 'Fagales', 'family': None}"), (12384, "{'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': 'Primulales', 'family': None}"), (12385, "{'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': 'Magnoliales', 'family': None}"), (12386, "{'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': 'Celastrales', 'family': None}")]

output = [(num, literal_eval(dct_rep)) for num, dct_rep in lst]

print(output) # [(45, {'kingdom': 'Plantae', 'phylum': None, 'class': None, 'order': None, 'family': None}), ...]
print(output[0][1]['kingdom']) # Plantae

列表推導將每個 dict 表示轉換為真正的 dict。 之后,您可以以更自然的方式訪問數據。

我會看eval

test_dict = eval(list[0][1])

注意:不建議在生產代碼中這樣做,因為它可以運行任何 python 代碼

暫無
暫無

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

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