Like the lambda
works:
Lambda is a real-time function definition, but works as a normal function.
lamda_soma_um = lambda x: x + 1
def func_soma_um(x):
return x + 1
lambda_soma_um(5) == func_soma_um(5)
In your case, the lambda function is receiving a dictionary and returning the value of the key price
negative (has a -
(minus sign) before the x['price']
).
That is, if the lambda function defined is applied to each row in your list the returns would be respectively -100, -138, -15 and -1.
From this point on, I believe the doubt is in relation to function sorted
. When a callable
is passed as a parameter in kw key
, the Sorted function will pass each item in your list to the callable
and will use the return to order in ascending order.
Considering the return of each item on your list and ordering them increasingly, we will have -138, -100, -15, -1.
>>> sorted(dic, key = lambda x: -x['price'])
[{'name': 'wine', 'price': 138}, {'name': 'bread', 'price': 100}, {'name': 'meat', 'price': 15}, {'name': 'water', 'price': 1}]
When Voce adds [:2]
you are picking up the first 2 items from the list.