Sorting the tuples of tuples in alphabetical order
<p>I have a list of tuples<br>
<code>[((A,B),2),((C,B),3)]</code>
Which I need to sort as</p>

<pre><code>[((A,B),2),((B,C),3)]
</code></pre>

<p>I need all the tuples to be in alphabetical order using the <code>sorted()</code> method. I have used <code>key = lambda x : x[0]</code> but doesn't work. Any ideas?</p>

<p>Since @AmiTarovy solved it, but his method not include sorting on second element of outer tuple, when there is two or more <code>tuple</code> elements with same first element.</p>

<p>So here is another solution, that also make a sort for second argument of outer tuple.</p>

<pre><code>&gt;&gt;&gt; from operator import itemgetter
&gt;&gt;&gt; tups = [(('A','B'),2),(('C','B'),3), (('A','B'),1)]
&gt;&gt;&gt; sorted(tups, key=itemgetter(0,1))
[(('A', 'B'), 1), (('A', 'B'), 2), (('C', 'B'), 3)]
</code></pre>

<p>If you want to sort only by first tuple</p>

<pre><code>&gt;&gt;&gt; from operator import itemgetter
&gt;&gt;&gt; tups = [(('A','B'),2),(('C','B'),3), (('A','B'),1)]
&gt;&gt;&gt; sorted(tups, key=itemgetter(0))
[(('A', 'B'), 2), (('A', 'B'), 1), (('C', 'B'), 3)]
</code></pre>

<p><strong>UPDATE</strong></p>

<p>Time consumption. Input data is 100 records of</p>

<pre><code>((random.choice(string.ascii_uppercase), random.choice(string.ascii_uppercase)), random.randint(0,100))
</code></pre>

<p><em>Results</em>:</p>

<p>@AmiTarovy answer with sorting <em>only by first element of tuple</em></p>

<pre><code>python3 -m timeit -s "import random; import string; tups = [((random.choice(string.ascii_uppercase), random.choice(string.ascii_uppercase)), random.randint(0,100)) for i in range(100)]" 'from operator import itemgetter; [(sorted(t[0]), t[1]) for t in tups]'
10000 loops, best of 3: 42.7 usec per loop
10000 loops, best of 3: 43.2 usec per loop
10000 loops, best of 3: 43.9 usec per loop
</code></pre>

<p>My answer with sorting <em>only by first element of tuple</em></p>

<pre><code>python3 -m timeit -s "import random; import string; tups = [((random.choice(string.ascii_uppercase), random.choice(string.ascii_uppercase)), random.randint(0,100)) for i in range(100)]" 'from operator import itemgetter; sorted(tups, key=itemgetter(0))'
10000 loops, best of 3: 36.1 usec per loop
10000 loops, best of 3: 36.6 usec per loop
10000 loops, best of 3: 37.9 usec per loop
</code></pre>

<p>My answer with <em>whole sorting</em>, but first element in priority</p>

<pre><code>python3 -m timeit -s "import random; import string; tups = [((random.choice(string.ascii_uppercase), random.choice(string.ascii_uppercase)), random.randint(0,100)) for i in range(100)]" 'from operator import itemgetter; sorted(tups, key=itemgetter(0,1))'
10000 loops, best of 3: 61 usec per loop
10000 loops, best of 3: 60.2 usec per loop
10000 loops, best of 3: 60.6 usec per loop
</code></pre>

python python-3.x