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)]?
An alternative approach, very close to your own example:
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...operator.itemgetter(1,0)
returns a tuple formed from the second, and then the first item. That is, iff=operator.itemgetter(1,0)
thenf(x)
returns(x[1],x[0])
.You just want standard
tuple
comparing, but in reversed mode: