Search code examples
pythonmaxdefaultdict

how collections.defaultdict.get work in max statement's key paramter--- python


I have read these post 1, 2, 3, but I still can not figure out following python code:

>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
...     d[k] += 1
...
>>> lis = ['m', 'i', 's', 'p']
>>> max(lis, key=d.get)
'i'

I know the times that a letter occurs stored in d. And when I input:

>>> d.get
<built-in method get of collections.defaultdict object at 0x7f506ed8d710>

It said that get is a method. Why it dose not use parenthesis? And what kind of data form it returns?


Solution

  • max accepts a keyword argument -- a "key" function. e.g.:

    max(iterable, key=some_function)
    

    Which (I'm guessing) is how you're using it (instead of max(iterable, function))

    The "key" function will be called for every element in the iterable and the result of the "key" function is used to compare elements.

    So, in your case, the element for which d.get returns the maximal value will be returned.

    d is your defaultdict. d.get(key) returns the value associated with that key -- and the things which are getting passed to it are keys that are in d. So you're picking out the key which has the maximal value.