簡體   English   中英

如何按值對Python dict的鍵進行排序

[英]How to sort a Python dict's keys by value

我有一個看起來像這樣的字典

{ "keyword1":3 , "keyword2":1 , "keyword3":5 , "keyword4":2 }

我想將其轉換為DESC並創建一個僅包含關鍵字的列表。 例如,這將返回

["keyword3" , "keyword1" , "keyword4" , "keyword2"]

我發現的所有例子都使用lambda,我對此並不是很強。 有沒有辦法可以循環使用它,並按我的方式對它們進行排序 謝謝你的任何建議。

PS:如果能有所幫助,我可以用不同的方式創建最初的dict。

你可以用

res = list(sorted(theDict, key=theDict.__getitem__, reverse=True))

(您不需要Python 2.x中的list

theDict.__getitem__實際上相當於lambda x: theDict[x]

(lambda只是一個匿名函數。例如

>>> g = lambda x: x + 5
>>> g(123)
128

這相當於

>>> def h(x):
...   return x + 5
>>> h(123)
128

>>> d={ "keyword1":3 , "keyword2":1 , "keyword3":5 , "keyword4":2 }
>>> sorted(d, key=d.get, reverse=True)
['keyword3', 'keyword1', 'keyword4', 'keyword2']

我總是這樣做....使用排序方法有優勢嗎?

keys = dict.keys()
keys.sort( lambda x,y: cmp(dict[x], dict[y]) )

哎呦沒讀過關於不使用lambda =的部分(

我想出這樣的事情:

[k for v, k in sorted(((v, k) for k, v in theDict.items()), reverse=True)]

KennyTM的解決方案更好:)

不可能對dict進行排序,只能獲得已排序的dict的表示。 Dicts固有的順序較少,但其他類型,如列表和元組,則不是。 所以你需要一個排序表示,它將是一個列表 - 可能是一個元組列表。 例如,

'''
Sort the dictionary by score. if the score is same then sort them by name 
{ 
 'Rahul'  : {score : 75} 
 'Suhas' : {score : 95} 
 'Vanita' : {score : 56} 
 'Dinesh' : {score : 78} 
 'Anil'  : {score : 69} 
 'Anup'  : {score : 95} 
} 
'''
import operator

x={'Rahul' : {'score' : 75},'Suhas' : {'score' : 95},'Vanita' : {'score' : 56}, 
   'Dinesh' : {'score' : 78},'Anil' : {'score' : 69},'Anup' : {'score' : 95} 
  }
sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))
print sorted_x

輸出:

[('Vanita', {'score': 56}), ('Anil', {'score': 69}), ('Rahul', {'score': 75}), ('Dinesh', {'score': 78}), ('Anup', {'score': 95}), ('Suhas', {'score': 95})]

暫無
暫無

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

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