您现在的位置是:课程教程文章

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

2023-12-15 21:33课程教程文章 人已围观

python中,不同类型的元素相互转换使用,可以方便我们的代码适应当时的代码环境。本文小编就向大家介绍python中字典与列表相互转换的方法。字符串转列表使用eval函数或exec函数,字典转字符串使用json。

一、字符串转字典

使用eval函数

str_test = "{'a': 1, 'b': 2}"
dict_test = eval(str)
print dict_test

使用exec函数

s = '{"name":"redhat","age":"10"}'
print type(s)
exec('c=' +s)
print c,"查看c的内容"
print  "查看c的类型",type(c)

输出

<type 'str'>
{'age': '10', 'name': 'redhat'} 查看c的内容
查看c的类型 <type 'dict'>

字典转字符串

使用json

import json
dict_1 = {'name':'linux','age':18}
dict_string = json.dumps(dict_1)print(type(dict_string))#输出:<class 'str'>

以上就是python中字符串与字典相互转换的方法,希望能对你有所帮助哦~

课程教程:python中字符串与字典相互转换的方法

上一篇:java中Scanner是什么?怎么用?

下一篇:没有了

站点信息

  • 文章统计篇文章