Lambda function to return higher value from a list of dictionaries

Asked

Viewed 137 times

0

Good evening. Could someone explain to me how the lambda function below works? I’m not understanding why it returns the highest value in the dictionary. Another thing I’d like to know, the 'x' is representing every dictionary within the list and not the list itself, would you tell me why? Thank you.

dic = [
    {"name": "bread", "price": 100},
    {"name": "wine", "price": 138},
    {"name": "meat", "price": 15},
    {"name": "water", "price": 1}
]    
sorted(dic, key = lambda x: -x['price'])[:2]

1 answer

1

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.