按值对字典排序,然后按Python3键按字母顺序排序

2024-04-23 21:56:25 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一本字典:

h=[('a',5), ('f', 3), ('b',3), ('c',3), ('d',1), ('e',4) ]

我想把它分为:

^{pr2}$

我可以用Python 2解决这个问题,方法如下:

sortedList= sorted(h.iteritems(),key=lambda(k,v):(-v,k))

我可以用类似的方法来接近Python 3:

import operator
sortedList =sorted(h.items(), key=operator.itemgetter(1,0) , reverse=True)

但结果是这样的

[('a',5), ('e',4), ('f',3), ('c',3), ('b',3),  ('d',1)]

我怎样才能扭转这种局面?在


Tags: 方法lambdakeyimporttrue字典itemsoperator