0

How do we sort dictionary by values in Python 2.3 when all we got is the dict.sort() taking no arguments. I can do the sorting using sorted(dict.items(), lambda x, y: cmp(x[1], y[1]), reverse=True) in newer Python.

What is needed is this: Example:

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

After sort:

[('c':3),('a':2),('b':1)]

Any hint please ? Thanks !

Levon
  • 138,105
  • 33
  • 200
  • 191
Poker Prof
  • 169
  • 5
  • 15

2 Answers2

6

So many things we take for granted in newer versions...

Anyways, Schwartzian Transform:

>>> l = [(-x[1], x) for x in d.items()]
>>> l.sort()
>>> l2 = [x[1] for x in l]
>>> l2
[('c', 3), ('a', 2), ('b', 1)]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
3

From the documentation: "The sort() method takes an optional argument specifying a comparison function of 2 arguments (list items) which should return -1, 0, or 1 depending on whether the 1st argument is considered smaller than, equal to, or larger than the 2nd argument"

So you want something like

lst = d.items()
lst.sort(lambda a,b: b[1]-a[1])

which returns

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

Edit: the lambda function is a comparator. For an ordinary, ascending sort, it should return a value <0 if a<b, ==0 if a==b, and >0 if a>b. The easy way to get this is a-b.

We want to sort in reversed order - so we reverse the sign of the comparator, returning a value <0 if a>b (etc)... and the easy way to get this is b-a.

We are sorting on the second member of each item, so the comparator becomes b[1]-a[1], as above.

Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
  • Sir could you kindly please explain briefly what does the lambda a,b: b[1]-a[1] does in helping to reverse sort the 2nd element of the tuple in the list??? – Poker Prof Jun 15 '12 at 03:01
  • Thx, so when its value is >0 (which should happen for the tuple with the biggest second element ie (c,3)), then the tuple will be 'printed' to the list first, and then the lambda will compare again and find the second biggest number and print the tuple and so on – Poker Prof Jun 15 '12 at 09:13