Python按照list dict key进行排序过程解析
作者:青春叛逆者 时间:2023-12-06 08:19:06
在做项目的时候,遇到这样的数据:
"trends": [
{
"name": "Rick Gates",
"promoted_content": null,
"query": "%22Rick+Gates%22",
"tweet_volume": 135732,
"url": "http://twitter.com/search?q=%22Rick+Gates%22"
},
{
"name": "#TheBachelorette",
"promoted_content": null,
"query": "%23TheBachelorette",
"tweet_volume": 91245,
"url": "http://twitter.com/search?q=%23TheBachelorette"
},
{
"name": "#KremlinAnnex",
"promoted_content": null,
"query": "%23KremlinAnnex",
"tweet_volume": 42654,
"url": "http://twitter.com/search?q=%23KremlinAnnex"
},
{
"name": "#LHHH",
"promoted_content": null,
"query": "%23LHHH",
"tweet_volume": 35252,
"url": "http://twitter.com/search?q=%23LHHH"
}]
我需要做的就是根据tweet_volume的数值对trends里的元素进行排序。
实现代码:
把上面数据以字典的方式获取,相当于把取出的就是后面的列表,即
trends=[
{
"name": "Rick Gates",
"promoted_content": null,
"query": "%22Rick+Gates%22",
"tweet_volume": 135732,
"url": "http://twitter.com/search?q=%22Rick+Gates%22"
},
{
"name": "#TheBachelorette",
"promoted_content": null,
"query": "%23TheBachelorette",
"tweet_volume": 91245,
"url": "http://twitter.com/search?q=%23TheBachelorette"
},
{
"name": "#KremlinAnnex",
"promoted_content": null,
"query": "%23KremlinAnnex",
"tweet_volume": 42654,
"url": "http://twitter.com/search?q=%23KremlinAnnex"
},
{
"name": "#LHHH",
"promoted_content": null,
"query": "%23LHHH",
"tweet_volume": 35252,
"url": "http://twitter.com/search?q=%23LHHH"
}]
trends = sorted(trends,key = lambda e:e['tweet_volume'],reverse = True)
考虑到有些数据是NULL,因此需要提前做个处理,对于空的tweet_volume设置为0,完整代码:
for item in trends:
if(item.get('tweet_volume') is None):
item['tweet_volume'] = 0
trends = sorted(trends,key = lambda e:.get('tweet_volume') ,reverse = True)
建议用get方式获取,空值或数据不存在这样不会报错。
在Python文档中看到一种性能更高的方法
通过使用 operator 模块的 itemgetter 函数,可以非常容易的排序这样的数据结构
因此上面的程序可以改写成
from operator import itemgetter
for item in trends:
if(item.get('tweet_volume') is None):
item['tweet_volume'] = 0
trends = sorted(trends,key = itemgetter('tweet_volume'),reverse = True)
来源:https://www.cnblogs.com/liangliangzz/p/12625934.html
标签:Python,list,dict,key
0
投稿
猜你喜欢
Numpy中如何创建矩阵并等间隔抽取数据
2023-01-14 16:21:16
GoLang调用链可视化go-callvis使用介绍
2023-07-16 06:39:59
mysql 5.7.18 绿色版下载安装教程
2024-01-20 02:23:30
Python常用数据库接口sqlite3和MySQLdb学习指南
2024-01-16 00:53:56
MySQL中数据导入恢复的简单教程
2024-01-20 15:28:04
python关于变量名的基础知识点
2023-07-27 14:21:43
科讯商业版中用到的ajax空间与分页函数
2024-04-17 10:05:45
Django限制API访问频率常用方法解析
2022-06-24 18:20:13
高性能WEB开发 JS、CSS的合并、压缩、缓存管理
2023-01-02 11:03:26
使用python根据端口号关闭进程的方法
2022-12-26 01:58:41
用python实现爬取奥特曼图片实例
2022-09-23 00:25:18
Python pip配置国内源的方法
2021-02-18 14:53:55
python学习数据结构实例代码
2023-09-20 22:56:32
Pycharm安装并配置jupyter notebook的实现
2022-11-14 14:24:28
详解Python中datetime库的使用
2021-03-31 20:14:13
python中的各种运算符介绍
2021-08-09 12:49:04
Python如何实现FTP功能
2021-10-22 15:08:25
Python 时间戳之获取整点凌晨时间戳的操作方法
2023-10-10 19:42:33
Python描述符descriptor使用原理解析
2022-03-24 20:12:48
基于Oracle多库查询方法(分享)
2024-01-13 12:09:03