[英]How to sort dictionary based on values and if multiple keys have same values then sort by keys
a = [1,1,1,11,2,2,2,2,2,3,3,3,3,4,4,4,4,8,11,8,8,5,11,7,7,7,7,7,]
freq = dict()
for i in a :
freq[i] = freq.get(i, 0) +1
fsort = dict(sorted(freq.items(), key=lambda item:item[1], reverse=True))
print(fsort)
上面的代碼計算數字的頻率並返回一個頻率字典,在這個階段字典是根據值排序的。 現在如何按降序對具有相同值的鍵進行排序? 這是代碼的 output 和預期的 output :
Output:
{2: 5, 7: 5, 3: 4, 4: 4, 1: 3, 11: 3, 8: 3, 5: 1}
Expected Output:
{7: 5, 2: 5, 4: 4, 3: 4, 11: 3, 1: 3, 8: 3, 5: 1}
您可以使用元組作為鍵。 特別是(value, key)
形式的元組:
dict(sorted(freq.items(), key=lambda item: item[::-1], reverse=True))
對於您的 dict,您可以簡單地使用key=lambda x: (x[1], x[0])
進行排序
對於您的代碼,您還可以使用來自collection
模塊的計數器,如下所示:
freq = Counter(a)
您可以反轉每個鍵值對並取每個鍵值對的負值(無需設置reverse=True
):
dict(sorted(freq.items(),key=lambda item:(-item[1],-item[0])))
如果您需要對鍵進行升序排序,對值進行降序排序(反之亦然),這種方法可以讓您更加靈活。 您只需要更改 lambda function 中的標志即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.