[英]Sort dictionary by value, then by key
嘿,我正在嘗試按值從最高值到最低值對字典進行排序。 Howevet 我希望通過鍵對具有相同值的項目進行排序。
以下代碼不起作用
dictionary = {"Sophie": 23, "Alfred": 23, "Zelda":22, "Betty":23}
sorted(dictionary.items(), key=lambda t: t[::-1])
Output:
[('Zelda', 22), ('Alfred', 23), ('Betty', 23), ('Sophie', 23)]
預期 output:
[('Alfred', 23), ('Betty', 23), ('Sophie', 23), ('Zelda', 22)]
按遞減值排序,然后按鍵(按字母順序)
由於您想使用一個鍵(值)按降序排序,而一個輔助鍵(名稱)按升序排序,因此簡單地顛倒排序順序是行不通的。 相反,您應該構造一個值和名稱的元組,並將值取反以按降序對其進行排序:
sorted(dictionary.items(), key=lambda t: (-t[1], t[0]))
這是他更現代的解決方案,只能在python3.x
中使用,這與問題所采用的方法相同。而不是t[::-1]
是您需要使用的索引t: (-t[1], t[0])
。 -t[1]
按升序對名稱進行排序,因為它已被否定。 t[0]
按降序對鍵進行排序。 這是代碼:
dictionary = {"Sophie": 23, "Alfred": 23, "Zelda":22, "Betty":23}
reversed_dict= dict(sorted(dictionary.items(), key=lambda t: (-t[1], t[0])))
print(reversed_dict)
Output:
{'Alfred': 23, 'Betty': 23, 'Sophie': 23, 'Zelda': 22}
這是更便攜的解決方案,適用於 python 的所有版本。此方法要求您在開始之前導入operator
庫。 sorted(dictionary.items(), key=operator.itemgetter(0))
按升序對名稱進行排序,然后sorted(reversed_dict, key=operator.itemgetter(1), reverse=True))
按降序對鍵進行排序。
這是代碼:
import operator
dictionary = {"Sophie": 23, "Alfred": 23, "Zelda":22, "Betty":23}
reversed_dict = sorted(dictionary.items(), key=operator.itemgetter(0))
reversed_dict = dict(sorted(reversed_dict, key=operator.itemgetter(1), reverse=True))
print(reversed_dict)
Output:
{'Alfred': 23, 'Betty': 23, 'Sophie': 23, 'Zelda': 22}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.