Python将字符串转为字典最佳实践
在工作中我们经常会遇到数据类型之间的互转的问题,而通常我们请求一些API借口返回的结果就是字符串,但是格式是Json的,在Python中转为字典是最易处理的,所以这里记录一下在Python下把字符串转为字典的三种方法。
方法一: 通过内置函数eval
Source Code:
#!/usr/bin/env python3
#Author: nock.chenstr_info = "{'name': 'nock', 'age': 14}"
dict_info = eval(str_info)print("string info type is -->: %s" % (type(str_info)))
print("dict info type is -->: %s" % (type(dict_info)))
复制代码
Result:
string info type is -->: <class 'str'>
dict info type is -->: <class 'dict'>
复制代码
不过使用eval有一个安全性问题,示例如下:
Source Code:
#!/usr/bin/env python3
#Author: nock.chenstr_info = input('input str info: ')
dict_info = eval(str_info)print("dict_info is >%s< " % dict_info)
复制代码
Result:
input str info: __import__('os').system('ls')
collector_data.py
test.py
Download
dict_info is >0<
复制代码
如上所示当我们输入__import__('os').system('ls')
的时候会打印出脚本所存目录下的文件,如果传入一个rm -rf *
之类的命令,那则会把所有改目录下的东西删除掉;当然我们这么去用的场景会非常好少,也不可能有人会这么传值,不过这里说明一下。
方法二: 通过json
模块处理
Source Code:
#!/usr/bin/env python3
#Author: nock.chenimport jsonstr_info = '{"name": "nock", "age": 18}'
dict_info = json.loads(str_info)print("string info type is -->: %s" % (type(str_info)))
print("dict info type is -->: %s" % (type(dict_info)))
复制代码
Result:
string info type is -->: <class 'str'>
dict info type is -->: <class 'dict'>
复制代码
使用json
模块进行转换也存在一个问题,由于json
语法规定 数组或对象之中的字符串必须使用双引号,不能使用单引号, 官网上有一段描述是:
报错示例如下:
#!/usr/bin/env python3
#Author: nock.chenimport json
str_info = "{'name': 'nock', 'age': 18}"
dict_info = json.loads(str_info)
复制代码
报错结果如下:
Traceback (most recent call last):File "test.py", line 7, in <module>dict_info = json.loads(str_info)File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/__init__.py", line 319, in loadsreturn _default_decoder.decode(s)File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/decoder.py", line 339, in decodeobj, end = self.raw_decode(s, idx=_w(s, 0).end())File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/decoder.py", line 355, in raw_decodeobj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
复制代码
方法三: 通过ast
模块处理
Source Code:
#!/usr/bin/env python3
#Author: nock.chenimport ast
str_info = '{"name": "nock", "age": 18}'
dict_info = ast.literal_eval(str_info)print("string info type is -->: %s" % (type(str_info)))
print("dict info type is -->: %s" % (type(dict_info)))s_info = "{'name': 'nock', 'age': 18}"
d_info = ast.literal_eval(s_info)print("s info type is -->: %s" % (type(s_info)))
print("d info type is -->: %s" % (type(d_info)))
复制代码
Result:
string info type is -->: <class 'str'>
dict info type is -->: <class 'dict'>
s info type is -->: <class 'str'>
d info type is -->: <class 'dict'>
复制代码
使用ast.literal_eval
进行转换既不存在使用json
模块进行转换的问题,也不存在使用eval
模块进行转换的安全性问题,因此推荐大家使用ast.literal_eval
的方法。
Python将字符串转为字典最佳实践相关推荐
- Python 将字符串转为字典
引言 在工作中遇到一个小问题,需要将一个 Python 的字符串转为字典,比如字符串: user_info = '{"name" : "john", " ...
- 将字符串转为16进制数_Python 如何将字符串转为字典
问题:需要将一个 Python 的字符串转为字典,比如字符串: user_info = '{"name" : "john", "gender" ...
- python 请求头_Python爬虫:将headers请求头字符串转为字典
第一种方法 如上图所示,然后复制粘贴到pycharm里,存放到字典里 然后使用ctrl+r快捷键打开替换功能,并勾选Regex 替换源为:(.?): (.?)$ 替换为:"$1": ...
- python编程之美pdf_GitHub - Farolding/toPdf: 爬取“Python编程之美:最佳实践指南”制作PDF电子书...
准备工作 爬取HTML页面转成PDF需要用到wkhtmltopdf工具,下载地址:https://wkhtmltopdf.org/downloads.html ,pdfkit是wkhtmltopdf的 ...
- python 神经网络 多进程_Pytorch多进程最佳实践
预备知识 模型并行( model parallelism ):即把模型拆分放到不同的设备进行训练,分布式系统中的不同机器(GPU/CPU等)负责网络模型的不同部分 -- 例如,神经网络模型的不同网络层 ...
- [转载] python string 字符串转换为字典 dict
参考链接: Python | 将列表字符串转换为字典 dict = eval(string)
- python中fasta转为字典
1.fasta转为字典 # 功能:读取解压后的*.fasta文件,将内容按键值对形式存为字典 # 输入: ## fasta_name:解压后的文件名 # 输出: ## fa_dict:包含描述和序列的 ...
- 用Python远程登陆服务器的最佳实践
来源 | Python编程时光(ID: Cool-Python) 在使用 Python 写一些脚本的时候,在某些情况下,我们需要频繁登陆远程服务去执行一次命令,并返回一些结果. 在 shell 环境中 ...
- 第二周python作业——字符串、字典、列表
第二周作业 字符串 基础 进阶 字典 列表 1. 基础题 2. 进阶题 3. 列表推导式 第二周作业 选择题 填空题 编程题 字符串 基础 输入一个字符串,打印所有奇数位上的字符(下标是1,3,5,7 ...
最新文章
- 揭晓飞桨平台提速秘诀:INT8量化加速实现“事半功倍”
- SAP Spartacus lazy load 的一个例子 - User Module
- 世界卫生组织高血压防治指南_建立对团队和组织的信任的指南
- JAVA反射系列之Method,java.lang.reflect.Method的使用。
- UIKit框架-基础控件Swift版本: 7.UISwitch方法/属性详解
- nginx报错unknown directive 锘? in D:\nginx/conf/nginx.conf:3
- 链表的实现(Java语言描述)
- mysql undo表空间增长_undo表空间太大解决办法
- addEventListener 简析
- 计算机上面的清除键是什么符号,电脑上删除键是哪一个
- LInux 的流量限制
- 抽象思维能力训练随感
- GNU C++ 智能指针3-- 解析_Sp_counted_base类
- taohui.org.cn建站历程
- ipad使用的PDF书籍没有目录怎么办?
- obsidian vim模式切换输入法
- 【实践】python 机器码 实现一机一码
- element中下拉框select在长页面滚动时,下拉弹框没有跟随下拉框跑路
- 马斯克反悔:毫米波雷达重新上车,最快下个月就发布
- 期刊介绍|中科院一区8+期刊,影响因子飞涨,国人友好,明显扩刊趋势!
热门文章
- 金三银四大厂面经总结,淘汰了80%的Java面试者
- zabbix修改tomcat监控端口
- linux 文件乱码_RedHatlinux系统虚机启动后/etc/fstab中的文件系统未能挂载上
- 35岁学嵌入式合适吗_保姆级攻略来了!嵌入式冰箱该怎么选?看这篇就够了
- python中snip_我终于弄懂了Python的装饰器(三)
- 计算机一级插入页眉,2017年计算机一级WPS辅导:WPS中页眉页脚的设计技巧
- php while for 性能,PHP For While 循环
- Android设置按钮点击后变色(导航栏变色)
- 20211201:力扣第268周双周赛(上)
- 20200428:186周周赛下(leetcode1425)