-1

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?

Community
  • 1
  • 1
sydridgm
  • 1,012
  • 4
  • 16
  • 30
  • Is this copy-pasted and unedited from an actual interactive interpreter session you ran? It shouldn't have worked; the `key` argument to `max` is keyword-only. – user2357112 Apr 08 '16 at 04:18
  • @user2357112 sorry. my bad. – sydridgm Apr 08 '16 at 04:27
  • 1
    Consider using [collections.Counter](https://docs.python.org/2/library/collections.html#counter-objects). It has a `most_common()` method that does exactly what you're doing here. – Don Kirkby Apr 08 '16 at 04:31

1 Answers1

2

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.

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • 1
    Actually it's weird, because `max(lis, d.get)` should return `['m', 'i', 's', 'p']` (which is the maximum of `lis` and the function `d.get`) – wim Apr 08 '16 at 04:14
  • Try it and you will see what I mean – wim Apr 08 '16 at 04:17
  • 1
    @mgilson: The `key` argument is keyword-only. – user2357112 Apr 08 '16 at 04:17
  • @user2357112 -- Ahh, right. Yes, I overlooked that. Funny -- I even thought about how it looked weird to have the key function _not_ called by keyword. – mgilson Apr 08 '16 at 04:19