The other answers are all correct and explain well what lambda
and sorted
's key
parameter do.
However, to answer the question what key=lambda i:i[0]
does, in your code: Nothing at all!
More precisely, it tells sorted
to sort by the first element of the tuples that are in the list to be sorted, which is produced by kwargs.items()
, i.e. a list of (key, value)
tuples. But sorting by the first element is the default sorting behaviour for tuples anyway, and only if those are equal, it would sort by the second element, and so on. But since those are the (keys, values)
of a dictionary, there are no two tuples with the same first element, so using this particular key function is exactly the same as the default sort.
You can just as well use key = (args, tuple(sorted(kwargs.items())))
.
If you are asking why it does this: This function seems to be used for memoization, mapping the function parameters (stored in args
and kwargs
) to previously calculated values. For this, the kwargs
dictionary has to be transformed to a tuple, because a dictionary is not hashable, i.e. it can not be used as the key to another dictionary. And in order to ensure that the same dictionaries always result in the same tuples, it has to be sorted, because dictionaries are unordered.