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
  • 20,479
  • 50
  • 119
  • 154

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
  • 138,671
  • 33
  • 247
  • 280