【问题标题】:Filter list of dictionaries by value and then add other keys & values to filtered dictionary?按值过滤字典列表,然后将其他键和值添加到过滤字典?
【发布时间】:2020-06-19 21:22:01
【问题描述】:

我有一个字典列表:

    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'}]

我如何过滤掉例如 >0.9 的 'delta',然后查看该过滤字典中其他值和键的输出?它不应该搜索“无”相关值。

所以结果应该是这样的:

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

【问题讨论】:

  • 请展示您迄今为止尝试过的内容,如果有多个字典通过过滤器,请举例说明结果应该是什么样的示例。

标签: python list dictionary finance


【解决方案1】:
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)

这种方法返回所有满足条件的字典的列表,在这种情况下:

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

【讨论】:

    【解决方案2】:

    您也可以在“一个”行中执行此操作:

    [i for i in option_list_dict if
        (all(f.isnumeric() for f in i['delta'].split('.'))
         and float(i['delta']) > .9)]
    
    [{'strike_price': '1', 'bid_price': '0.25', 'delta': '0.94'}]
    

    【讨论】:

    • 不知何故我得到了这个错误:'NoneType'对象没有属性'split'。有什么办法解决这个问题?
    猜你喜欢
    • 2020-02-09
    • 2023-01-14
    • 2015-05-17
    • 2020-02-06
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    相关资源
    最近更新 更多