สำหรับการจัดการข้อมูลใน 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 ให้วิธีการถ่ายโอนข้อมูลแก่เรา ด้วยวิธีนี้ ออบเจ็กต์พจนานุกรมจะถูกแปลงเป็นสตริงโดยตรง
ตัวอย่าง
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: