4

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)]?

Damian
  • 449
  • 4
  • 11

3 Answers3

4

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]).

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Note: `itemgetter` with multiple items only works with python >2.5 – Shawn Chin Aug 16 '11 at 09:40
  • Is it possible to sort one as straight and second in reverse, i.e. [('a', 3), ('b', 2), ('c', 2), ('d', 1)]? – Damian Aug 16 '11 at 09:46
  • 1
    @Damian: You could do that by changing the integer to its negative: `sorted(d.items(),key=lambda x: (-x[1],x[0]))`. – unutbu Aug 16 '11 at 09:55
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)]
Roman Bodnarchuk
  • 29,461
  • 12
  • 59
  • 75
0

An alternative approach, very close to your own example:

sorted(d.items(), key=lambda x: (x[1], x[0]))
Nicola Musatti
  • 17,834
  • 2
  • 46
  • 55