如何在 Python 中將字典的字串表示形式轉換為字典?


為了將字串表示的字典轉換為原始字典,我們可以使用內建函式,例如 `eval()`、`json.load()` 和 `ast.literal_eval()`。首先,我們必須確保字串包含字典的有效表示形式。讓我們討論每個函式如何將字典的字串表示形式轉換為原始字典。

使用 `eval()` 函式

`eval()` 是 Python 的內建函式,它接受字串引數,將其解析為程式碼表達式,並計算該表示式。如果輸入表示式包含字典的字串表示形式,則 `eval()` 方法將其作為普通的 Python 字典返回。

語法

eval(expression[, globals[, locals]])

引數

  • expression: 它接收一個字串,然後將其解析並計算為 Python 表示式。

  • globals:這是一個可選引數,用於指定可用的全域性方法和變數。

  • locals:這也是一個可選引數,用於指定可用的區域性方法和變數。

返回值

返回表示式的輸出。

示例

使用 `eval()` 函式是最簡單的方法,但它很危險,因為它可能會執行注入到字串中的任何惡意程式碼。

String_dict = "{'1': 1, '2': 2, '3': 3}"
print("Input string represented dictionary: ",String_dict)
print(type(String_dict))

# use the eval method to convert the expression
dict_ = eval(String_dict)
print("Output: ", dict_)
print(type(dict_))

輸出

Input string represented dictionary:  {'1': 1, '2': 2, '3': 3}
<class 'str'>
Output:  {'1': 1, '2': 2, '3': 3}
<class 'dict'>

使用 `ast.literal_eval()` 函式

抽象語法樹 (ast) 是一個 Python 模組,它提供了一個名為 `literal_eval()` 的方法,該方法用於高效地將字串轉換為字典。

該方法絕不會執行程式碼,它只會解析表示式,並且只有在它是字面量時才返回,因此它是轉換字串的最安全方法。

語法

ast.literal_eval ( node_or_string )

示例

讓我們來看一個這個函式的例子。要使用 `literal_eval()` 函式,首先我們需要匯入 ast 包。

import ast

string_dict = "{'a': 1, 'b': 2, 'c': 3}"
print("Input string represented dictionary: ",string_dict)
print(type(string_dict))

# convert the string
dict_ = ast.literal_eval(string_dict)
print("Output: ", dict_)
print(type(dict_))

輸出

Input string represented dictionary:  {'a': 1, 'b': 2, 'c': 3}
<class 'str'>
Output:  {'a': 1, 'b': 2, 'c': 3}
<class 'dict'>

正如我們在上面的輸出中看到的,`ast.literal_eval()` 方法成功地計算了字串,並返回了 Python 字典物件。

示例

以下另一個例子

import ast
stringA = '{"Mon" : 3, "Wed" : 5, "Fri" : 7}'
# Given string dictionary
print("Given string : \n",stringA)
# using json.loads()
res = ast.literal_eval(stringA)
# Result
print("The converted dictionary : \n",res)

輸出

執行上面的程式碼得到以下結果

Given string : 
 {"Mon" : 3, "Wed" : 5, "Fri" : 7}
The converted dictionary : 
 {'Mon': 3, 'Wed': 5, 'Fri': 7}

使用 `json.loads()` 函式

`json.loads()` 是一個內建的 Python 函式,它將有效的字串轉換為 Python 物件。讓我們使用 `json.loads()` 方法將字典的字串表示形式轉換為原始字典物件。

語法

json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

在使用 `loads()` 方法之前,我們首先需要匯入 json 庫。

示例

在下面的例子中,我們可以看到 `loads()` 函式返回了一個字典,我們透過使用 `type()` 方法驗證了這一點。

import json

d = '{"Age": 7, "Gender": "Female", "Name": "Jennifer"}'
print("Input string represented dictionary: ",d)
print(type(d))

python_dict = json.loads(d)
print("Output: ", python_dict)
print(type(python_dict))

輸出

Input string represented dictionary:  {"Age": 7, "Gender": "Female", "Name": "Jennifer"}
<class 'str'>
Output:  {'Age': 7, 'Gender': 'Female', 'Name': 'Jennifer'}
<class 'dict'>

示例

以下是此函式的另一個示例

import json
stringA = '{"Mon" : 3, "Wed" : 5, "Fri" : 7}'
# Given string dictionary
print("Given string : \n",stringA)
# using json.loads()
res = json.loads(stringA)
# Result
print("The converted dictionary : \n",res)

輸出

執行上面的程式碼得到以下結果

Given string :
{"Mon" : 3, "Wed" : 5, "Fri" : 7}
The converted dictionary :
{'Mon': 3, 'Wed': 5, 'Fri': 7}

注意:如果鍵或值包含單引號,`json.loads()` 將引發錯誤。

更新於: 2023年8月24日

7K+ 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.