python中字符串與字典相互轉換的方法
python中,不同類型的元素相互轉換使用,可以方便我們的代碼適應當時的代碼環境。本文小編就向大家介紹python中字典與列表相互轉換的方法。字符串轉列表使用eval函數或exec函數,字典轉字符串使用json。
一、字符串轉字典
使用eval函數
str_test="{'a':1,'b':2}"
dict_test=eval(str)
printdict_test
使用exec函數
s='{"name":"redhat","age":"10"}'
printtype(s)
exec('c='+s)
printc,"查看c的內容"
print"查看c的類型",type(c)
輸出
{'age':'10','name':'redhat'}查看c的內容
查看c的類型
字典轉字符串
使用json
importjson
dict_1={'name':'linux','age':18}
dict_string=json.dumps(dict_1)print(type(dict_string))#輸出:
以上就是python中字符串與字典相互轉換的方法,希望能對你有所幫助哦~更多Python學習教程請關注IT培訓機構:千鋒教育。