簡體   English   中英

如何將字典轉換為按其值排序的鍵列表?

[英]How to convert a dictionary into a list of its keys sorted by its values?

我想獲得按其值排序的鍵列表,如果有任何關系,按字母順序排序。 我可以按值排序。 如果是關系,我面臨着問題。

對於字典:

aDict = {'a':8, 'one' : 1, 'two' : 1, 'three':2, 'c':6,'four':2,'five':1}

我試過這個:

sorted(aDict, key=aDict.get, reverse=True)

這給了我:

['a', 'c', 'three', 'four', 'two', 'five', 'one']

但我想要:

['a', 'c', 'four', 'three', 'five', 'one', 'two']

您可以使用返回元組的鍵函數。 如果第一個元素相等,則值將按元組的第二個元素排序。

>>> aDict = {'a':8, 'one' : 1, 'two' : 1, 'three':2, 'c':6,'four':2,'five':1}
>>> sorted(aDict, key=lambda x: (-aDict[x], x))
['a', 'c', 'four', 'three', 'five', 'one', 'two']

暫無
暫無

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

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