如何在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}
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
使用`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()`将引发错误。