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 )
示例1
让我们看一个使用这个函数的例子。要使用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字典对象。
示例2
以下是另一个示例。
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库。
示例1
在下面的示例中,我们可以看到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'>
示例2
以下是该函数的另一个示例。
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()将会抛出错误。