在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:热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短