[英]Sort a dictionary in python by values but maintaining the key order for equal values
可以說有一本字典
d = {"P1":77,"P2":89,"P3":77}
我想以下面的形式打印結果
P2:89
P1:77
P3:77
即按字典值排序,對於相等的值,首先是第一個(即P1在P3之前)
我做了以下
import collections
od = collections.OrderedDict(sorted(d.items(), key=lambda x:x[1], reverse=True))
od給出
OrderedDict([('P2', 89), ('P3', 77), ('P1', 77)])
如何在P3之前獲得P1?
做這個:
od = collections.OrderedDict(sorted(d.items(), key = lambda x:(-x[1],x[0])))
正如@Padraic所說,“你不能從最高到最低,從最低到最高。” 因此,您必須通過使排序函數看到最高數字作為最低數字來欺騙它。 它按鍵的自然順序進行子排序。
Python的sort
是一種穩定的排序,意味着如果項目比較相等,則項目保持原始順序。 如果您從OrderedDict
開始並僅對值進行排序,則它們將保持原始順序。 但是,在您的情況下,使用直接排序從最高到最低的鍵排序它們,而不是反轉排序,以使它們保持相同的鍵順序。
from collections import OrderedDict
d = OrderedDict([('P1',77),('P2',89),('P3',77)])
print sorted(d.items(),key=lambda x:-x[1])
d = OrderedDict([('P3',77),('P2',89),('P1',77)])
print sorted(d.items(),key=lambda x:-x[1])
[('P2', 89), ('P1', 77), ('P3', 77)]
[('P2', 89), ('P3', 77), ('P1', 77)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.