Python按照l(shuí)ist dict key進(jìn)行排序過(guò)程解析
在做項(xiàng)目的時(shí)候,遇到這樣的數(shù)據(jù):
"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"
}]
我需要做的就是根據(jù)tweet_volume的數(shù)值對(duì)trends里的元素進(jìn)行排序。
實(shí)現(xiàn)代碼:
把上面數(shù)據(jù)以字典的方式獲取,相當(dāng)于把取出的就是后面的列表,即
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)
考慮到有些數(shù)據(jù)是NULL,因此需要提前做個(gè)處理,對(duì)于空的tweet_volume設(shè)置為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方式獲取,空值或數(shù)據(jù)不存在這樣不會(huì)報(bào)錯(cuò)。
在Python文檔中看到一種性能更高的方法
通過(guò)使用 operator 模塊的 itemgetter 函數(shù),可以非常容易的排序這樣的數(shù)據(jù)結(jié)構(gòu)
因此上面的程序可以改寫(xiě)成
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)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- python中字典dict排序sorted的實(shí)現(xiàn)
- Python sorted對(duì)list和dict排序
- Python OrderedDict字典排序方法詳解
- Python 按字典dict的鍵排序,并取出相應(yīng)的鍵值放于list中的實(shí)例
- python 對(duì)key為時(shí)間的dict排序方法
- python中dict字典的查詢(xún)鍵值對(duì) 遍歷 排序 創(chuàng)建 訪(fǎng)問(wèn) 更新 刪除基礎(chǔ)操作方法
- python 字典(dict)按鍵和值排序
- Python中字典(dict)和列表(list)的排序方法實(shí)例
- Python中dict排序的兩種方法
相關(guān)文章
Django 查詢(xún)數(shù)據(jù)庫(kù)返回JSON的實(shí)現(xiàn)
和前端交互全部使用JSON,如何將數(shù)據(jù)庫(kù)查詢(xún)結(jié)果轉(zhuǎn)換成JSON格式,本文就來(lái)介紹一下,感興趣的小伙伴們可以參考一下2021-08-08
一文詳解Python中PO模式的設(shè)計(jì)與實(shí)現(xiàn)
在使用 Python 進(jìn)行編碼的時(shí)候,會(huì)使用自身自帶的編碼設(shè)計(jì)格式,比如說(shuō)最常見(jiàn)的單例模式等。本文將為大家介紹PageObject自動(dòng)化設(shè)計(jì)模式(PO模式)的設(shè)計(jì)與實(shí)現(xiàn),感興趣的可以了解一下2022-06-06

