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>In Python <code>_</code> (underscore) is a valid identifier and can be used as a variable name, e.g.</p>

<pre><code>&gt;&gt;&gt; _ = 10
&gt;&gt;&gt; print(_)
10
</code></pre>

<p>It can therefore also be used as the name of an argument to a lambda expression - which is like an unnamed function.</p>

<p>In your example <code>sorted()</code> passes tuples produced by <code>aDict.items()</code> to its <code>key</code> function.  The key function returns the first element of that tuple which <code>sorted()</code> then uses as the key, i.e that value to be compared with other values to determine the order.</p>

<p>Note that, in this case, the same result can be produced without a key function because tuples are naturally sorted according to the first element, then the second element, etc. So </p>

<pre><code>sorted(aDict.items())
</code></pre>

<p>will produce the same result. Because dictionaries can not contain duplicate keys, the first element of each tuple is unique, so the second element is never considered when sorting.</p>

python sorting lambda key