Search code examples
pythonpython-3.xlistdictionarystock

Long list creating sorted() TypeError: 'NoneType' object is not subscriptable


option_list is a list of dictionaries with strings.

This code works as long as the option_list list is not too large.

option_list = sorted(option_list, key = lambda option: option['expiration_date'])
option_list = sorted(option_list, key = lambda option: option['strike_price'], reverse=True)

It's sorting the option data by expiration date and strike price.

However, when the option_list list gets to an arbitrary-to-me length, it throws this error:

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-237-7fd70ddaa35a> in <module>()
      3 # option_list = sorted(option_list, key = lambda option: (option['expiration_date'], option['strike_price']))
      4 
----> 5 option_list = sorted(option_list, key = lambda option: option['expiration_date'])
      6 option_list = sorted(option_list, key = lambda option: option['strike_price'], reverse=True)
      7 

<ipython-input-237-7fd70ddaa35a> in <lambda>(i)
      3 # option_list = sorted(option_list, key = lambda option: (option['expiration_date'], option['strike_price']))
      4 
----> 5 option_list = sorted(option_list, key = lambda option: option['expiration_date'])
      6 option_list = sorted(option_list, key = lambda option: option['strike_price'], reverse=True)
      7 

TypeError: 'NoneType' object is not subscriptable

However, truncating the option_list list to an arbitrary number works again:

option_list = sorted(option_list[:-5000], key = lambda option: option['expiration_date'])

I've tried -1000, but that is not low enough.

Why does this happen, and how can I fix it so I don't have to cut off data?


Solution

  • Seems like your problem is missing data. Since the error is referencing to NoneTypes. Try filtering the missing data out first:

    no_missing_options = [o for o in option_list if o]
    option_list = sorted(no_missing_options , key=lambda x: x['expiration_date'])