Search code examples
pythondictionaryconcept

python return statement concept


I was trying to find the highest three values from a dictionary and I'm supposed to return the keys of that value I have come across this method

import heapq

def get_n_largest(n,dictionary):
    return heapq.nlargest(n,dictionary,dictionary.get)

From python docs I undetstand that nlargest needs to take in an integer, an iterable and a key if provided.

What I don't understand is what is the difference between dictionary.get() in the return statement and dictionary.get() when I try to print dictionary.get of my dictionary it returns

"built-in method get of dict object at 0x0000020E77B12168"

I have done some search but I cannot find concepts about it. Any help will be very much appreciated!


Solution

  • dictionary.get doesn't call the function, it is just a reference to the function dictionary.get. In order to call the function, you need to do dictionary.get(*args, **kwargs) And as far as to this - heapq.nlargest(n,dictionary,dictionary.get) I haven't looked at the docs for heapq. But apparently nlargest callable seems to be taking callable reference as third parameter. And in turn, nlargest might be calling callable somewhere in the logic as dictionary.get(*args, **kwargs)