如何在 Python 中根據字典的值對字典列表進行排序?


在本文中,我們將展示如何在 Python 中根據字典的值對字典列表進行排序。

排序一直是日常程式設計中一項有用的技術。Python 的字典經常用於各種應用中,從競賽到面向開發人員的應用(例如處理 JSON 資料)。在某些情況下,能夠根據字典的值過濾字典會很有用。

以下是完成此任務的兩種方法:

  • 使用 sorted() 和 itemgetter

  • 使用 sorted() 和 lambda 函式

什麼是字典?

字典是 Python 中關聯陣列資料結構的版本。字典是鍵值對的集合。每個鍵值對由一個鍵和與其關聯的值表示。

字典由用花括號括起來並用逗號分隔的鍵值對列表定義。每個鍵的值由冒號(:)分隔。

字典是一個有序的資料值集合,可以使用鍵訪問。字典是鍵值對映。dict() 是用於建立 dict 類例項的建構函式。字典中的元素順序是未定義的。可以迭代鍵、值或鍵值對。

使用 sorted() 和 Itemgetter

sorted() 函式

sorted() 函式返回給定可迭代物件的排序列表。

您可以在升序和降序之間進行選擇。數字按數字排序,而字串按字母順序排列。

語法

sorted(iterable, key=key, reverse=reverse)

引數

iterable - 它是一個序列。

key - 將執行以確定順序的函式。預設值為 None。

reverse - 布林表示式。True 表示升序排序,False 表示降序排序。預設值為 False。

Python 中的 Itemgetter

為了實現類似的功能,可以使用 Itemgetter 函式代替 lambda 函式。與 sorted() 和 lambda 相同,但具有不同的內部實現。它接受字典鍵並將它們轉換為元組。它最大限度地減少了開銷,同時速度更快、效率更高。

要使用itemgetter,必須匯入“operator”模組。

  • 效能 - 在效能方面,itemgetter 在時間方面優於 lambda 函式。

  • 簡潔 - 在訪問多個值時,itemgetter 看起來比 lambda 函式更簡單。

演算法(步驟)

以下是執行所需任務需要遵循的演算法/步驟:

  • 使用 import 關鍵字從 operator 模組匯入itemgetter以實現 itemgetter。

  • 建立一個變數來儲存輸入字典列表。

  • 使用sorted()函式(返回給定可迭代物件的排序列表)和 itemgetter 列印按分數排序的列表。

示例

以下程式使用 sorted() 和 itemgetter 返回按值排序的輸入字典列表:

# importing itemgetter from the operator module
# (for implementing itemgetter)
from operator import itemgetter
 
# Input list of dictionaries
inputList = [{"cricketer": "Dhoni", "score": 75},{"cricketer": "Virat Kohli", "score": 90},
   {"cricketer": "Hardik Pandya", "score": 65}]
 
print("The sorted list by score: ")
# printing the sorted list by score using the sorted() and itemgetter
print(sorted(inputList, key=itemgetter('score')))
 
print("\r")
 
# printing the sorted list by both cricketer, score using the sorted() and itemgetter
# Here Dhoni comes first since 'D' comes first then H, and V alphabetically 
print("The sorted list by both cricketer and score: ")
print(sorted(inputList, key=itemgetter('cricketer', 'score')))
 
print("\r")
 
# printing the sorted list by the score in descending order 
# using the sorted() and itemgetter
print("The sorted list by the score in descending order: ")
print(sorted(inputList, key=itemgetter('score'), reverse=True))

輸出

執行上述程式後,將生成以下輸出:

The sorted list by score: 
[{'cricketer': 'Hardik Pandya', 'score': 65}, {'cricketer': 'Dhoni', 'score': 75}, {'cricketer': 'Virat Kohli', 'score': 90}]

The sorted list by both cricketer and score: 
[{'cricketer': 'Dhoni', 'score': 75}, {'cricketer': 'Hardik Pandya', 'score': 65}, {'cricketer': 'Virat Kohli', 'score': 90}]

The sorted list by the score in descending order: 
[{'cricketer': 'Virat Kohli', 'score': 90}, {'cricketer': 'Dhoni', 'score': 75}, {'cricketer': 'Hardik Pandya', 'score': 65}]

使用 sorted() 和 lambda 函式

示例

以下程式使用 sorted() 和 lambda() 函式返回按值排序的輸入字典列表:

# Input list of dictionaries
inputList = [{"cricketer": "Dhoni", "score": 75},{"cricketer": "Virat Kohli", "score": 90},
   {"cricketer": "Hardik Pandya", "score": 65}]
 
print("The sorted list by score: ")
# printing the sorted list by score using the sorted() and lambda functions
print(sorted(inputList, key=lambda k: k['score']))
 
print("\r")
 
# printing the sorted list by both cricketer, and score using the sorted() and lambda functions
# Here Dhoni comes first since 'D' comes first then H, and V alphabetically 
print("The sorted list by both cricketer and score: ")
print(sorted(inputList, key=lambda k: (k['cricketer'], k['score'])))
 
print("\r")
 
# printing the sorted list by the score in descending order 
# using the sorted() and lambda functions
print("The sorted list by the score in descending order: ")
print(sorted(inputList, key=lambda k: k['score'], reverse=True))

輸出

執行上述程式後,將生成以下輸出:

The sorted list by score: 
[{'cricketer': 'Hardik Pandya', 'score': 65}, {'cricketer': 'Dhoni', 'score': 75}, {'cricketer': 'Virat Kohli', 'score': 90}]

The sorted list by both cricketer and score: 
[{'cricketer': 'Dhoni', 'score': 75}, {'cricketer': 'Hardik Pandya', 'score': 65}, {'cricketer': 'Virat Kohli', 'score': 90}]

The sorted list by the score in descending order: 
[{'cricketer': 'Virat Kohli', 'score': 90}, {'cricketer': 'Dhoni', 'score': 75}, {'cricketer': 'Hardik Pandya', 'score': 65}]

結論

在這篇文章中,我們學習瞭如何使用兩種不同的方法根據值對字典列表進行排序。在本文中,我們還學習了 lambda 函式和 item getter。

更新於: 2023年1月31日

515 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.