Can someone help me understand what is actually occurring in the answer provided? I don’t understand how the function knows to parse through the dictionaries within hn_clean. If I were to run get_num_comments(hn_clean) it results in an error because list indices must be integers, but in the function most_comments = max(hn_clean, key=get_num_comments) it somehow knows to just apply the function to the dictionaries within the list. Help would be much appreciated!
There is a way we can actually tell functions like min(), max(), and sorted() how to sort complex objects like dictionaries and lists of lists. We do this by using the optional key argument. The official Python documentation contains the following excerpts that describe how the argument works:
The key argument specifies a one-argument ordering function like that used for list.sort().
**key specifies a function* of one argument that is used to extract a comparison key from each list element. The key corresponding to each item in the list is calculated once and then used for the entire sorting process.*
The content does help us understand what exactly is happening. Let me know if you have some specific questions based on the content or not.
Thank you. The figure initially confused me in that the formula shouldn’t work on a list. I didn’t understand that the key arg functioned on each element within the list. I appreciate the assistance!