key argument for max?

Josiah Carlson jcarlson at uci.edu
Thu Oct 21 19:35:23 CEST 2004


"Batista, Facundo" <FBatista at uniFON.com.ar> wrote:
> [Steven Bethard]
> 
> #- I was wondering if there's any plans to add a "key" argument to max
> #- (and min) like was done for sort(ed)?  I fairly often run into a
> #- situation where I have something like:
> #- 
> #- counts = {}
> #- for item in iterable:
> #-     counts[item] = counts.get(item, 0) + 1
> #- _, max_item = max((count, item) for item, count in counts.items())
> #- 
> #- It would be nice to be able to write that last like like:
> #- 
> #- max(counts, key=counts.__getitem__)
> 
> Don't understand why you're doing that. I would do:
> 
> >>> lst = ['a', 'b', 'c', 'a', 'd', 'b', 'a']
> >>> counts = {}
> >>> for item in lst:
> 	counts[item] = counts.get(item, 0) + 1
> 
> >>> counts
> {'a': 3, 'c': 1, 'b': 2, 'd': 1}
> >>> max_item = max(counts.values())
> >>> max_item
> 3


You missed what he was asking for.  He doesn't care about 3, he cares
about the item that has the value of 3; 'a'.

I've done similar things to what Steven is doing now, though I am unsure
as to whether the key=getter mechanism should be used, or whether
something else is necessary.

 - Josiah




More information about the Python-list mailing list