1

I have a data structure like:

[ ["id1", 123], ["id2", 1], ["id3", 6] ]

and I would like to ordered it (descendingly) according to the second variable, like this:

[ ["id1", 123], ["id3", 6], ["id2", 1] ]

I could write up a little function for doing that, but I am almost sure there's a cool one liner way of doing it, isn't there? Thanks.

nunos
  • 19,269
  • 49
  • 116
  • 153

1 Answers1

7

You can do it using sorted and itemgetter:

>>> a = [ ["id1", 123], ["id2", 1], ["id3", 6] ]
>>> from operator import itemgetter
>>> sorted(a, key=itemgetter(1), reverse=True)
[['id1', 123], ['id3', 6], ['id2', 1]]

If you purely wanted a one-liner (no import), then you can lambda it:

>>> sorted(a, key=lambda L: L[1], reverse=True)
Jon Clements
  • 132,101
  • 31
  • 237
  • 267