12

I have the following tuple, which contains tuples:

MY_TUPLE = (
    ('A','Apple'),
    ('C','Carrot'),
    ('B','Banana'),
)

I'd like to sort this tuple based upon the second value contained in inner-tuples (i.e., sort Apple, Carrot, Banana rather than A, B, C).

Any thoughts?

Huuuze
  • 15,528
  • 25
  • 72
  • 91

4 Answers4

25
from operator import itemgetter

MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=itemgetter(1)))

or without itemgetter:

MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=lambda item: item[1]))
Markus Jarderot
  • 86,735
  • 21
  • 136
  • 138
  • 2
    Of note: if the value you're sorting by can have duplicates, you can fallback to another value by giving additional arguments to [`itemgetter`](http://docs.python.org/library/operator.html#operator.itemgetter), e.g. `itemgetter(1, 0)`. – Petr Viktorin Dec 03 '11 at 18:22
  • Should be "from operator import itemgetter". – paragbaxi Apr 12 '12 at 22:19
7

From Sorting Mini-HOW TO

Often there's a built-in that will match your needs, such as str.lower(). The operator module contains a number of functions useful for this purpose. For example, you can sort tuples based on their second element using operator.itemgetter():

>>> import operator 
>>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
>>> map(operator.itemgetter(0), L)
['c', 'd', 'a', 'b']
>>> map(operator.itemgetter(1), L)
[2, 1, 4, 3]
>>> sorted(L, key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]

Hope this helps.

mwilliams
  • 9,946
  • 13
  • 50
  • 71
2
sorted(my_tuple, key=lambda tup: tup[1])

In other words, when comparing two elements of the tuple you're sorting, sort based on the return value of the function passed as the key parameter.

Eli Courtwright
  • 186,300
  • 67
  • 213
  • 256
-2

I achieved the same thing using this code, but your suggestion is great. Thanks!

templist = [ (line[1], line) for line in MY_TUPLE ] 
templist.sort()
SORTED_MY_TUPLE = [ line[1] for line in templist ]
Huuuze
  • 15,528
  • 25
  • 72
  • 91
  • Ouch! Why make three copies of everything? Seems excessive to me. For a large collection of data, this will be pretty slow. – S.Lott Oct 21 '08 at 17:58