[英]Sorting a Dictionary by Value then Alphabetically by Key Python3
Let's say I have a dictionary like: 假设我有一个字典:
h=[('a',5), ('f', 3), ('b',3), ('c',3), ('d',1), ('e',4) ]
I want it sorted like: 我希望它排序如下:
[('a',5), ('e',4), ('b',3), ('c',3), ('f',3), ('d',1)]
I can solve this with Python 2 with something like this: 我可以用Python 2解决这个问题:
sortedList= sorted(h.iteritems(),key=lambda(k,v):(-v,k))
I can get really close in Python 3 with something like this: 我可以通过以下方式在Python 3中非常接近:
import operator
sortedList =sorted(h.items(), key=operator.itemgetter(1,0) , reverse=True)
but it comes out like this 但它就是这样出来的
[('a',5), ('e',4), ('f',3), ('c',3), ('b',3), ('d',1)]
How can I reverse the tiebreaker operation? 如何扭转决胜局的操作?
You can use this call to the sorted function in python 3: 你可以使用这个调用python 3中的排序函数:
sortedList = sorted(h, key=lambda k: (-k[1], k[0]))
This will give the same result as the python 2 sorting: 这将得到与python 2排序相同的结果:
[('a',5), ('e',4), ('b',3), ('c',3), ('f',3), ('d',1)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.