screen link: https://app.dataquest.io/m/355/list-comprehensions-and-lambda-functions/7/passing-functions-as-arguments
could somebody explain how this code below works: particularly : max(hn_clean, key=key_function)
most_comments = max(hn_clean, key=key_function)
Thank you very much beforehand!
It will first apply passed function as an argument to items of iterable and then will sort based on the result given by that function.
I think this image given in mission explaining it well
In the first block of code, lines 1 - 2, we define a function called ‘key_function’ which is just a function that takes in a dictionary, which we call dict_, as input and returns the value corresponding to ‘numComments’ which is a key in that dictionary.
In the last line, the max(hn_clean, key=key_function) function finds the highest number of comments in hn_clean (the JSON list) by iterating through the JSON list using key_function, which we defined above, to create a list of all values of the dictionary key ‘numComments’ then it finds the max value in that created list. This max value is then assigned to the variable called ‘most_comments’.
I hope this explanation helps you better understand how it works @ilhomjon656798 . If you have any more questions feel free to ask.
I was wondering instead of using
why cant we just use hn_clean[’'numComments"]?
The created function confuse me the most, how can a the function knows to find the key “numComments”, but outside of the function it says i can only pass an int not str
lol I just confused myself with my own code, so basically i can use any string not only just hn_clean. I thought here i have to put the json name