Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

min() on collections.defaultdict() returns max count

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)
like image 606
IT Ninja Avatar asked Oct 16 '25 20:10

IT Ninja


1 Answers

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]).

like image 83
BrenBarn Avatar answered Oct 18 '25 09:10

BrenBarn