在 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:
廣告