Sorting the content of a dictionary by the value and by the key

对着背影说爱祢 提交于 2020-01-13 03:49:46

问题


Sorting the content of a dictonary by the value has been throughly described already, so it can be acheived by something like this:

d={'d':1,'b':2,'c':2,'a':3}
sorted_res_1= sorted(d.items(), key=lambda x: x[1]) 
# or
from operator import itemgetter 
sorted_res_2 = sorted(d.items(), key=itemgetter(1)) 

My question is, what would be the best way to acheive the following output:

[('d', 1), ('b', 2), ('c', 2), ('a', 3)] instead of [('d', 1), ('c', 2), ('b', 2), ('a', 3)]

so that the tuples are sorted by value and then by the key, if the value was equal.

Secondly - would such be possible for reversed: [('a', 3), ('b', 2), ('c', 2), ('d', 1)] instead of [('a', 3), ('c', 2), ('b', 2), ('d', 1)]?


回答1:


The sorted key parameter can return a tuple. In that case, the first item in the tuple is used to sort the items, and the second is used to break ties, and the third for those still tied, and so on...

In [1]: import operator

In [2]: d={'d':1,'b':2,'c':2,'a':3}

In [3]: sorted(d.items(),key=operator.itemgetter(1,0))
Out[3]: [('d', 1), ('b', 2), ('c', 2), ('a', 3)]

operator.itemgetter(1,0) returns a tuple formed from the second, and then the first item. That is, if f=operator.itemgetter(1,0) then f(x) returns (x[1],x[0]).




回答2:


You just want standard tuple comparing, but in reversed mode:

>>> sorted(d.items(), key=lambda x: x[::-1])
[('d', 1), ('b', 2), ('c', 2), ('a', 3)]



回答3:


An alternative approach, very close to your own example:

sorted(d.items(), key=lambda x: (x[1], x[0]))


来源:https://stackoverflow.com/questions/7076108/sorting-the-content-of-a-dictionary-by-the-value-and-by-the-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!