Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chuyển đổi đối tượng từ điển thành chuỗi trong Python

Trong thao tác dữ liệu Python, có thể cần chuyển đối tượng từ điển thành chuỗi. Có thể thực hiện theo các cách sau.

Sử dụng str()

Cách trực tiếp: áp dụng str() với từ điển làm tham số. Kiểm tra kiểu bằng type() trước và sau chuyển đổi.

Ví dụ

DictA = {"Mon": "2 pm", "Wed": "9 am", "Fri": "11 am"}
print("Given dictionary : \n", DictA)
print("Type : ", type(DictA))
# Sử dụng str
res = str(DictA)
# In kết quả
print("Result as string:\n", res)
print("Type of Result: ", type(res))

Kết quả

Chạy đoạn mã trên cho kết quả sau:

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:

Sử dụng json.dumps

Module json cung cấp dumps(). Từ điển được chuyển trực tiếp thành chuỗi.

Ví dụ

import json
DictA = {"Mon": "2 pm", "Wed": "9 am", "Fri": "11 am"}
print("Given dictionary : \n", DictA)
print("Type : ", type(DictA))
# Sử dụng json.dumps
res = json.dumps(DictA)
# In kết quả
print("Result as string:\n", res)
print("Type of Result: ", type(res))

Kết quả

Chạy đoạn mã trên cho kết quả sau:

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: