ต้องการแปลง dictionary object เป็น string object
ใช้ str()
ใช้ str() โดยตรง ตรวจสอบ type ก่อนและหลัง
ตัวอย่าง
DictA = {"Mon": "2 pm", "Wed": "9 am", "Fri": "11 am"}
print("Given dictionary : \n", DictA)
print("Type : ", type(DictA))
res = str(DictA)
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() แปลง dict เป็น JSON string (double quotes)
ตัวอย่าง
import json
DictA = {"Mon": "2 pm", "Wed": "9 am", "Fri": "11 am"}
print("Given dictionary : \n", DictA)
print("Type : ", type(DictA))
res = json.dumps(DictA)
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: