在Python中,将字符串转换为字典通常有两种方法:
1. 使用`json.loads()`函数
2. 使用`eval()`函数
下面是使用这两种方法的示例:
使用`json.loads()`
import json
字符串形式的字典
string = '{"name": "John", "age": 30}'
转换为字典
dictionary = json.loads(string)
print(dictionary) 输出:{'name': 'John', 'age': 30}
使用`eval()`
字符串形式的字典
string = '{"name": "John", "age": 30}'
转换为字典
dictionary = eval(string)
print(dictionary) 输出:{'name': 'John', 'age': 30}
需要注意的是,`eval()`函数会执行传入的字符串作为代码,因此在使用时要格外小心,避免执行恶意代码。相对而言,`json.loads()`函数更安全,因为它只能解析JSON格式的字符串。