簡體   English   中英

如何同時按鍵和值對字典進行排序? 事實上,在我的字典中,鍵是字符串,我想按字母順序排序,值是數字

[英]how to sort a dict by keys and values at the same time? in fact, in my dict, keys are strings and i want to sort alphabetically and values are number

我想首先按從最大值到最小值的值對下面的字典進行排序,當兩個值的數量相同時,我想按字母順序對其進行排序? 我的問題:

the_dict={ 'Action': 3, 'Romance':2, 'Adventure':1 , 'Comedy': 2 , 'History'=1, 'Horror'=3} 

我用過了:

for key, value in sorted(dict.items(), reverse=True, key=lambda x:(x[1], x[0])):
     print(key,':',value)

我得到了以下結果:

'Action': 3
'Horror':3
'Comedy': 2
'Romance':2
'History':1
'Adventure':1

但我的想法結果是:

'Action': 3
'Horror':3
'Comedy': 2
'Romance':2
'Adventure':1
'History':1

我怎樣才能達到我最喜歡的結果?

由於您的價值觀是 int,您可以這樣做:

for key, value in sorted(the_dict.items(), key=lambda x: (-x[1], x[0])):
    print(key, ':', value)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM