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)]?
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])
.
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)]
An alternative approach, very close to your own example:
sorted(d.items(), key=lambda x: (x[1], x[0]))