1. 程式人生 > 程式設計 >Python按照list dict key進行排序過程解析

Python按照list dict key進行排序過程解析

在做專案的時候,遇到這樣的資料:

"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","query": "%23TheBachelorette","tweet_volume": 91245,"url": "http://twitter.com/search?q=%23TheBachelorette"
        },{
          "name": "#KremlinAnnex","query": "%23KremlinAnnex","tweet_volume": 42654,"url": "http://twitter.com/search?q=%23KremlinAnnex"
        },{
          "name": "#LHHH","query": "%23LHHH","tweet_volume": 35252,"url": "http://twitter.com/search?q=%23LHHH"
        }]

我需要做的就是根據tweet_volume的數值對trends裡的元素進行排序。

實現程式碼:

把上面資料以字典的方式獲取,相當於把取出的就是後面的列表,即

trends=[
        {
          "name": "Rick Gates","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)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。