Search code examples
pythonlistdictionaryfinance

Filter list of dictionaries by value and then add other keys & values to filtered dictionary?


I have a list of dictionaries:

    option_list_dict = [{'strike_price': '1', 'bid_price': '0.25', 'delta': '0.94' }, 
    {'strike_price': '1.5', 'bid_price': '0.15', 'delta': '0.88'},
    {'strike_price': '2', 'bid_price': '0.05', 'delta': 'None'}, 
    {'strike_price': '2.5', 'bid_price': '0.31', 'delta': '0.25'}]

How can I filter out for example, a 'delta' of >0.9 and then see an output of the other values and keys that are in that filtered dictionary? And it should not search for 'None' related values.

So the result should look something like:

search_for_delta >0.9 = {'strike_price': '1', 'bid_price': '0.25', 'delta': '0.94'}

Solution

  • option_list_dict = [{'strike_price': '1', 'bid_price': '0.25', 'delta': '0.94' }, 
        {'strike_price': '1.5', 'bid_price': '0.15', 'delta': '0.88'},
        {'strike_price': '2', 'bid_price': '0.05', 'delta': 'None'}, 
        {'strike_price': '2.5', 'bid_price': '0.31', 'delta': '0.25'}]
    
    result = []
    
    for dict in option_list_dict:
        try:
            if float(dict['delta']) > 0.9:
                result.append(dict)
        except:
            pass
    
    print(result)
    

    This approach returns a list of all the dictionaries that satisfy the condition, in this case:

    result = [{'strike_price': '1', 'bid_price': '0.25', 'delta': '0.94'}]