Python Forum
Beignner of python --- Heapq - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Beignner of python --- Heapq (/thread-13298.html)



Beignner of python --- Heapq - david191624 - Oct-09-2018

I am a Beignner of python, I found a example on code inside the book about how to use heapq , but I don't understand the code meaning on the lambda function: Big Grin

What key=lambda s: s['price'] does inside the code ? what return ? or output ?


import heapq

portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])



RE: Beignner of python --- Heapq - buran - Oct-09-2018

first of all, Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.

second, let's explain what key does. From the docs:
Quote:key, if provided, specifies a function of one argument that is used to extract a comparison key from each element in the iterable: key=str.lower Equivalent to: sorted(iterable, key=key, reverse=True)[:n]

lambda define so-called anonymous functions (function that is defined without a name). In this case it takes as argument one item from portfolio and it returns the value for key price. i.e. we compare nodes using their price.
It is same as

import heapq

def share_price(company):
    return company['price']
 
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
cheap = heapq.nsmallest(3, portfolio, key=share_price)
expensive = heapq.nlargest(3, portfolio, key=share_price)