How to use filter with itemgetter while using the operator?

654 Views Asked by At

I have a dictionary with people's name and stock value and I would like to get the tuple consists of the name and maximum value of stock. Here is an issue: some of stock value is not available and inserted as 'NaN' and hence, I would like to filter them.

max_stock = max(stock.iteritems(), key=operator.itemgetter(1))

How can I put a filter option in the piece of code ?

1

There are 1 best solutions below

0
On BEST ANSWER

You'd have to filter what items go into max(). You could use a generator expression there:

max_stock = max((kv for kv in stock.iteritems() if kv[1] != 'NaN'),
                key=operator.itemgetter(1))

Take into account that this can raise a ValueError now if there are no items left after filtering! You could use a try...except statement to handle that case:

try:
    max_stock = max((kv for kv in stock.iteritems() if kv[1] != 'NaN'),
                    key=operator.itemgetter(1))
except ValueError:
    # no stock at all
    max_stock = None