在 Python 中将字典对象转换为字符串

pythonserver side programmingprogramming更新于 2026/1/13 11:56:17

对于 Python 中的数据操作,我们可能会遇到将字典对象转换为字符串对象的情况。这可以通过以下方式实现。

使用 str()

在这个简单的方法中,我们通过将字典对象作为参数传递来简单地应用 str()。我们可以在转换前后使用 type() 检查对象的类型。

示例

DictA = {"Mon": "2 pm","Wed": "9 am","Fri": "11 am"}
print("给定字典:\n", DictA)
print("类型 : ", type(DictA))
# using str
res = str(DictA)
# 打印结果
print("结果为字符串:\n", res)
print("结果类型: ", type(res))

输出

运行上述代码得到以下结果 −

给定字典:
{'Mon': '2 pm', 'Wed': '9 am', 'Fri': '11 am'}
类型:
结果为字符串:
{'Mon': '2 pm', 'Wed': '9 am', 'Fri': '11 am'}
结果类型:

使用 json.dumps

json 模块为我们提供了 dumps 方法。通过此方法将字典对象直接转换为字符串。

示例

import json
DictA = {"Mon": "2 pm","Wed": "9 am","Fri": "11 am"}
print("给定字典:\n", DictA)
print("类型 : ", type(DictA))
# using str
res = json.dumps(DictA)
# 打印结果
print("结果为字符串:\n", res)
print("结果类型: ", type(res))

输出

运行上述代码得到以下结果 −

给定字典:
{"Mon":'2 pm','Wed':'9 am','Fri':'11 am'}
类型:
结果为字符串:
{"Mon":"2 pm","Wed":"9 am","Fri":"11 am"}
结果类型:

相关文章


有用资源