I want to make a list of the largest two and smallest two items in a list of dictionaries based on a dictiony key in this case 'price' - as shown below in the code - using the heapq module two functions nlargest() and nsmallest() i tried this code and it didn't work :
import heapq
portfolio = [
{'name': 'FACEBOOK', 'shares': 100, 'price': 91.1},
{'name': 'MICROSOFT', 'shares': 50, 'price': 543.22},
{'name': 'APPLE', 'shares': 200, 'price': 21.09},
{'name': 'AMAZON', 'shares': 35, 'price': 31.75}
]
cheap = heapq.nsmallest(2, portfolio)
expensive = heapq.nlargest(2, portfolio)
print('the two cheap stocks:', cheap)
print('the two expensive stocks:', expensive)
Then i finded a solution with lambda it did work ! but i didn't get it : this is the version with the solution piece included and it works but i didn't understand the use of lambda in this context:
import heapq
portfolio = [
{'name': 'FACEBOOK', 'shares': 100, 'price': 91.1},
{'name': 'MICROSOFT', 'shares': 50, 'price': 543.22},
{'name': 'APPLE', 'shares': 200, 'price': 21.09},
{'name': 'AMAZON', 'shares': 35, 'price': 31.75}
]
# the lambda solution
cheap = heapq.nsmallest(2, portfolio, key=lambda x: x['price'])
expensive = heapq.nlargest(2, portfolio, key=lambda x: x['price'])
print('the two cheap stocks:', cheap)
print('the two expensive stocks:', expensive)
this is the ouput it's exactly what i expected:
the two cheap stocks: [{'name': 'APPLE', 'shares': 200, 'price': 21.09}, {'name': 'AMAZON', 'shares': 35, 'price': 31.75}]
the two expensive stocks: [{'name': 'MICROSOFT', 'shares': 50, 'price': 543.22}, {'name': 'FACEBOOK', 'shares': 100, 'price': 91.1}]
I hope finding a good explanation of the use of lambda in the argument key of the function nlargest or nsmallest and thanks in advance.