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

417次阅读
没有评论
python中字符串与字典相互转换的方法

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中字符串与字典相互转换的方法,希望能对你有所帮助哦~

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-06-29发表,共计532字。
新手QQ群:570568346,欢迎进群讨论 Python51学习