Question

When using min() on a defaultdict object, it strangely returns the maximum if used on a dict counting indices of a string.

For example:

>>> import collections
>>> defaultdict=collections.defaultdict
>>> x=defaultdict(int)
>>> string="lol I am a lol noob"
>>> for k in string:
    x[k]+=1


>>> x
defaultdict(<type 'int'>, {'a': 2, ' ': 5, 'b': 1, 'I': 1, 'm': 1, 'l': 4, 'o': 4, 'n': 1})
>>> min(x.items())
(' ', 5)
Was it helpful?

Solution

items() returns the items as (key, value) tuples. This means that when they are compared by min (or by anything else), they are compared first by key and then by value. Since ' ' is the "minimum" string (i.e., ' ' < 'a', ' ' < 'b', etc.), that is what is returned.

You need to tell min to use the second item of the tuple as the comparison key. Do min(x.items(), key=lambda a: a[1]).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top