Ignore None values and skip to next value?

1.6k views Asked by At

This list of dictionaries changes regularly.

search_option = [{'strike_price': '1', 'bid_price': '0.25', 'implied_volatility': '0.94' }, 
{'strike_price': '3.5', 'bid_price': '0.20', 'implied_volatility': '0.88'},
{'strike_price': '2', 'bid_price': '0.05', 'implied_volatility': None}, 
{'strike_price': '3.5', 'bid_price': '0.31', 'implied_volatility': '0.25'}]

Here the code searches for an option with an implied volatility below 0.9.

for option_list in search_option:
    if option_list is not None:
        option_list = ([i for i in search_option if float(i["implied_volatility"]) < 0.90])
    print(option_list)

I occasionally get this error:

float() argument must be a string or a number, not 'NoneType'

My question is, how can I leave the search the same (implied_volatility < 0.9) while at the same time ignoring the None values? In other words, if it's 'None' then skip to the next available option.

4

There are 4 answers

1
Max On BEST ANSWER

Try this:

option_list = ([i for i in search_option if i["implied_volatility"] and float(i["implied_volatility"]) < 0.90])

You also do not have to iterate through the search_option with a for loop you can just use the code above to replace it.

0
Oscar916 On
for i in search_option:
if i['implied_volatility'] is not None and float(i['implied_volatility']) < 0.9 :
     print(i)

Is this what you want?

0
Egino Cepheus On

Add if i["implied_volatility"] is not None before your conditional. Yur entire list comprehension thus becomes:

[i for i in search_option if i["implied_volatility"] is not None if float(i["implied_volatility"]) < 0.90]

This is the list comprehension equivalent to a nested conditional.

0
Balaji Ambresh On

Here you go:

option_list = [so for so in search_option if float(so['implied_volatility'] or '0.95') < 0.90]
print(option_list)

Output

[{'strike_price': '3.5', 'bid_price': '0.20', 'implied_volatility': '0.88'}, {'strike_price': '3.5', 'bid_price': '0.31', 'implied_volatility': '0.25'}]