Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 max function using value in defaultdict as key not working

Suppose model is a defaultdict, and num is a set

>>> model
>>> defaultdict(<function <lambda> at 0x11076f758>, {1: 3, 2: 2, 4: 1})
>>> num
>>> {1, 2, 3, 4, 5, 6}

I want to get the item from num that has maximum value in model, and the following code works fine in Python2

>>> # python 2.7.6
>>> max(num, key=model.get)
>>> 1

But it doesn't work in Python3,

>>> # python 3.3.3
>>> max(num, key=model.get)
>>> TypeError: unorderable types: NoneType() > int()

I can use max(num, key=lambda k:model[k]) to get it work in Python3, but if the item in num is not in the model, it will be added. This will modify model.

I am wondering why model.get doesn't work in Python3, and how can I do it without modifying model.

like image 206
mitchelllc Avatar asked Jan 21 '14 19:01

mitchelllc


1 Answers

Use key=lambda x: model.get(x, 0).

defaultdict.get by default returns None if the item is not found. Python 2 allows ordered comparisons (like less-than and greater-than) on different types, but Python 3 doesn't. When Python 3 tries to find the max, it tries to see if the value for one key is greater than another. If one of the values is None, it fails with the error you saw. The solution is to make your key function return zero instead of None for missing values.

like image 190
BrenBarn Avatar answered Oct 29 '22 17:10

BrenBarn