python中字符串与字典相互转换的方法

2023-12-14 10:30:48网络知识悟空

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培训机构:筋斗云。

发表评论: