0

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!

Selcuk
  • 57,004
  • 12
  • 102
  • 110
Sanny
  • 79
  • 1
  • 9
  • Shouldnt you be calling `get` as a function in `dictionary.get`? – GKE Mar 11 '19 at 05:09
  • The third argument to the `nlargest` method is a key, or a callable, that's why you are passing a _pointer_ to the `get` method. That's why it shows you the name of the method and the memory location when you `print` it. – Selcuk Mar 11 '19 at 05:30
  • Please read answers to this question if you want to understand calling a function without parentheses. https://stackoverflow.com/questions/21785933/purpose-of-calling-function-without-brackets-python – Sach Mar 11 '19 at 05:47

2 Answers2

1

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)

ranjith
  • 361
  • 4
  • 14
1

There is no difference. It's exactly the same .get method in both cases. In the return statement it will be applied to a key from the dictionary (an element of the iterable), ie. called as get(k). In the print it not applied, ie. called with a dictionary key and printed get value which is the function reference.

Mike
  • 1,107
  • 6
  • 7