![](/img/trans.png)
[英]Python sort dictionary by descending values and then by keys alphabetically
[英]I want to sort a dictionary descending by number and then ascending alphabetically
我有這個代碼
L = ['c', 'c', 'b', 'a','b']
from collections import Counter
import numpy as np
x = Counter(L)
dict1 = {k: v for k, v in sorted(x.items(), key=lambda item: -item[1])}
print(dict1)
它給了我{'c': 2, 'b': 2, 'a': 1}
但我希望它返回給我: {'b': 2,'c': 2, 'a': 1}
如果我把它變成一個列表並使用sorted
它會返回我這個[('a', 1), ('b', 2), ('c', 2)]
這不是我想要的,因為這樣,該列表將失去按數字降序排序。
b
和c
具有相同的優先級,因為它們具有相同的值。 因此,它們的順序保持不變,並且由於c
首先出現在L
中,它也將首先出現在x
和它的 dict 理解表達式中。 如果您希望b
出現在c
之前,您可以顯式地將輔助鍵添加到key
lambda 中:
dict1 = {k: v for k, v in sorted(x.items(), key=lambda item: (-item[1], item[0]))}
# Here ---------------------------------------------------------------^
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.