要把字典转换为字符串,可以使用json库中的dumps()函数。下面是使用json库将字典转换为字符串的示例代码:
import jsondict_obj = {'name': 'Alice', 'age': 25}# 将字典转换为字符串json_str = json.dumps(dict_obj)print(json_str)输出结果:
{"name": "Alice", "age": 25}另外,如果想要将字典转换为格式化的字符串,可以使用dumps()函数的indent参数。例如:
import jsondict_obj = {'name': 'Alice', 'age': 25}# 将字典转换为格式化的字符串json_str = json.dumps(dict_obj, indent=4)print(json_str)输出结果:
{ "name": "Alice", "age": 25} 
