如何按值对Python字典的键进行排序

25

我有一个类似这样的字典

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

我想将其按值从大到小排序,并创建一个只包含关键字的列表。例如,这将返回

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

所有我找到的示例都使用lambda表达式,而我对此并不很熟悉。是否有一种方法可以在循环时进行排序?谢谢任何建议。

PS:如果更改初始字典有助于解决问题,则可以尝试。


可能是按值对Python字典进行排序的重复问题。 - Teepeemm
@Teepeemm,我认为这个版本的问题更好。 - Karl Knechtel
5个回答

45

你可以使用

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

)


+1 用这段程序可以按数字顺序排序包含整数的文件名。names = {} for f in sys.argv[1:] : robj = re.search( "([0-9]+)", f ) if robj is not None : names[f] = int(robj.group(1))res = list(sorted(names,key=names.getitem)) print "\n".join(res) - David Poole
在3.x中也不需要使用list调用。 - Karl Knechtel

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

2
我一直都是这样做的……使用sorted方法有什么优势吗?
keys = dict.keys()
keys.sort( lambda x,y: cmp(dict[x], dict[y]) )

抱歉,我没有注意到不允许使用Lambda表达式的部分 =(


2
我会设计出类似以下的解决方案:
[k for v, k in sorted(((v, k) for k, v in theDict.items()), reverse=True)]

但是KennyTM的解决方案更好 :)


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

output:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接