您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页python中字符串与字典相互转换的方法

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

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务