2010-08-05 64 views
18

排序Python字典有字典,看起來像這樣我如何通過價值

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

而且我想將它轉化DESC創造只是關鍵字的列表。例如,這將返回

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

所有的例子,我發現使用Lambda和我不是很強大的這一點。有沒有辦法通過這個循環,並按照我去?感謝您的任何建議。 PS:我可以創建不同的初始字典,如果它可以幫助。

+0

[按值排序Python字典]的可能重複(http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value) – Teepeemm 2015-09-08 20:42:27

回答

40

你可以使用

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 

+0

非常好。謝謝! – 2010-08-05 18:13:55

+0

+1使用它來對包含整數的文件名進行數字排序。如果robj不是None: names [f] = int f:sys.argv [1:]: robj = re.search(「([0-9] +)」,f) (robj.group(1)) res = list(sorted(names,key = names。__getitem__)) print「\ n」.join(res) – 2011-10-25 15:08:37

2

我都是這樣做的....在那裏使用排序方法的優點?

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

哎呦didnt閱讀部分關於不使用的λ=(

+0

這是我真正需要學習的東西。謝謝! – 2010-08-05 18:28:26

2

我會拿出這樣的:

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

KennyTM's solution是好得多:)

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

不可能對字典進行排序,只能得到已排序的字典的表示形式。字典本質上是無序的,但其他類型,如列表和元組,不是。所以你需要一個排序表示,這將是一個列表 - 可能是一個元組列表。例如,

''' 
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',{ '得分':56}),( '阿尼爾',{ '得分':69}),( '的Rahul',{'得分''75}),('Dinesh',{'score':78}),('Anup',{'score':95}),('Suhas',{'score':95})]