在 Python 中将字典对象转换成字符串
在 Python 中进行数据操作时,我们可能会遇到将字典对象转换成字符串对象的情况。可以通过以下方式实现。
使用 str()
在此直接方法中,我们简单地将字典对象作为参数传递应用 str()。我们可以在转换前后使用 type() 检查对象类型。
示例
DictA = {"Mon": "2 pm","Wed": "9 am","Fri": "11 am"}
print("Given dictionary : \n", DictA)
print("Type : ", type(DictA))
# using str
res = str(DictA)
# Print result
print("Result as string:\n", res)
print("Type of Result: ", type(res))输出
运行以上代码,得到以下结果:-
Given dictionary :
{'Mon': '2 pm', 'Wed': '9 am', 'Fri': '11 am'}
Type :
Result as string:
{'Mon': '2 pm', 'Wed': '9 am', 'Fri': '11 am'}
Type of Result:使用 json.dumps
json 模块提供了 dumps 方法。通过此方法,字典对象直接转换成字符串。
示例
import json
DictA = {"Mon": "2 pm","Wed": "9 am","Fri": "11 am"}
print("Given dictionary : \n", DictA)
print("Type : ", type(DictA))
# using str
res = json.dumps(DictA)
# Print result
print("Result as string:\n", res)
print("Type of Result: ", type(res))输出
运行以上代码,得到以下结果:-
Given dictionary :
{'Mon': '2 pm', 'Wed': '9 am', 'Fri': '11 am'}
Type :
Result as string:
{"Mon": "2 pm", "Wed": "9 am", "Fri": "11 am"}
Type of Result:
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP