How can Python convert a dictionary into a string?

To convert a dictionary to a string, you can use the dumps() function in the json library. Here is an example code using the json library to convert a dictionary to a string:

import json

dict_obj = {'name': 'Alice', 'age': 25}

# 将字典转换为字符串
json_str = json.dumps(dict_obj)

print(json_str)

The output result:

{"name": "Alice", "age": 25}

Additionally, if you want to convert a dictionary into a formatted string, you can use the indent parameter of the dumps() function. For example:

import json

dict_obj = {'name': 'Alice', 'age': 25}

# 将字典转换为格式化的字符串
json_str = json.dumps(dict_obj, indent=4)

print(json_str)

Output result:

{
    "name": "Alice",
    "age": 25
}
bannerAds