In the following Python script where \"aDict\" is a dictionary, what does \"_: _[0]\" do in the lambda function?
sorted(aDict.items(), key=lambda _: _[0])
In Python, lambda is used to create an anonymous function. The first underscore in your example is simply the argument to the lambda function. After the colon (i.e. function signature), the _[0]
retrieves the first element of the variable _
.
Admittedly, this can be confusing; the lambda component of your example could be re-written as lambda x: x[0]
with the same result. Conventionally, though, underscore variable names in Python are used for "throwaway variables". In this case, it implies that the only thing we care about in each dictionary item is the key. Nuanced to a fault, perhaps.