What is this doing in the Python lambda function?
<p>In the following Python script where "aDict" is a dictionary, what does "_: _[0]" do in the lambda function?</p>

<pre><code>sorted(aDict.items(), key=lambda _: _[0])
</code></pre>

<p>Lets pick that apart.</p>

<p>1) Suppose you have a dict, di:</p>

<pre><code>di={'one': 1, 'two': 2, 'three': 3}
</code></pre>

<p>2) Now suppose you want each of its key, value pairs:</p>

<pre><code> &gt;&gt;&gt; di.items()
 [('three', 3), ('two', 2), ('one', 1)]
</code></pre>

<p>3) Now you want to sort them (since dicts are unordered):</p>

<pre><code>&gt;&gt;&gt; sorted(di.items())
[('one', 1), ('three', 3), ('two', 2)]
</code></pre>

<p>Notice that the tuples are sorted lexicographically -- by the text in the first element of the tuple. This is a equivalent to the <code>t[0]</code> of a series of tuples. </p>

<p>Suppose you wanted it sorted by the number instead. You would you use a <code>key</code> function:</p>

<pre><code>&gt;&gt;&gt; sorted(di.items(), key=lambda t: t[1])
[('one', 1), ('two', 2), ('three', 3)]
</code></pre>

<p>The statement you have <code>sorted(aDict.items(), key=lambda _: _[0])</code> is just using <code>_</code> as a variable name. It also does nothing, since <code>aDict.items()</code> produces tuples and if you did not use a key it sorts by the first element of the tuple anyway. The key function in your example is completely useless.</p>

<p>There might be a use case for the form (other than for tuples) to consider. If you had strings instead, then you would be sorting by the first character and ignoring the rest:</p>

<pre><code>&gt;&gt;&gt; li=['car','auto','aardvark', 'arizona']
&gt;&gt;&gt; sorted(li, key=lambda c:c[0])
['auto', 'aardvark', 'arizona', 'car']
</code></pre>

<p>Vs:</p>

<pre><code>&gt;&gt;&gt; sorted(li)
['aardvark', 'arizona', 'auto', 'car']
</code></pre>

<p>I still would not use <code>_</code> in the lambda however. The use of <code>_</code> is for a throway variable that has minimal chance of side-effects. Python has namespaces that mostly makes that worry not a real worry. </p>

<p>Consider:</p>

<pre><code>&gt;&gt;&gt; c=22
&gt;&gt;&gt; sorted(li, key=lambda c:c[0])
['auto', 'aardvark', 'arizona', 'car']
&gt;&gt;&gt; c
22
</code></pre>

<p>The value of <code>c</code> is preserved because of the local namespace inside the <code>lambda</code>. </p>

<p><em>However</em> (under Python 2.x but not Python 3.x) this can be a problem:</p>

<pre><code>&gt;&gt;&gt; c=22
&gt;&gt;&gt; [c for c in '123']
['1', '2', '3']
&gt;&gt;&gt; c
'3'
</code></pre>

<p>So the (light) convention became using <code>_</code> for a variable either in the case of a list comprehension or a tuple expansion, etc where you worry less about trampling on one of your names. The message is: If it is named <code>_</code>, I don't really care about it except right here...</p>

python sorting lambda key