Python – 從給定字典中獲取已排序的專案
Python 字典包含鍵值對。在某些情況下,我們需要根據鍵對字典中的專案進行排序。在本文中,我們將瞭解從字典中獲取排序輸出的不同方法。
使用 Operator 模組
Operator 模組具有 itemgetter 函式,該函式可以將 0 作為字典鍵的輸入引數索引。我們將 sorted 函式應用於 itemgetter 並獲取排序輸出。
示例
dict = {12 : 'Mon', 21 : 'Tue', 17: 'Wed'} import operator print("\nGiven dictionary", str(dict)) print ("sorted order from given dictionary") for k, n in sorted(dict.items(),key = operator.itemgetter(0),reverse = False): print(k, " ", n)
輸出
執行以上程式碼將得到以下結果:
Given dictionary {12: 'Mon', 21: 'Tue', 17: 'Wed'} sorted order from given dictionary 12 Mon 17 Wed 21 Tue
使用 Sorted 方法
sorted 方法可以直接應用於字典,它會對字典的鍵進行排序。
示例
dict = {12 : 'Mon', 21 : 'Tue', 17: 'Wed'} #Using sorted() print ("Given dictionary", str(dict)) print ("sorted order from given dictionary") for k in sorted(dict): print (dict[k])
輸出
執行以上程式碼將得到以下結果:
Given dictionary {12: 'Mon', 21: 'Tue', 17: 'Wed'} sorted order from given dictionary Mon Wed Tue
使用 dict.items()
我們也可以將 sorted 方法應用於 dict.items。在這種情況下,鍵和值都可以打印出來。
示例
dict = {12 : 'Mon', 21 : 'Tue', 17: 'Wed'} #Using d.items() print("\nGiven dictionary", str(dict)) print ("sorted order from given dictionary") for k, i in sorted(dict.items()): print(k,i)
輸出
執行以上程式碼將得到以下結果:
Given dictionary {12: 'Mon', 21: 'Tue', 17: 'Wed'} sorted order from given dictionary 12 Mon 17 Wed 21 Tue
廣告