![](/img/trans.png)
[英]Reassign some python dictionary keys to be values and other values to be keys, within a list of dictionaries
[英]Filter list of dictionaries by value and then add other keys & values to filtered dictionary?
我有一個字典列表:
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 的“增量”,然后查看該過濾字典中其他值和鍵的 output? 它不應該搜索“無”相關值。
所以結果應該類似於:
search_for_delta >0.9 = {'strike_price': '1', 'bid_price': '0.25', 'delta': '0.94'}
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'}]
您也可以在“一個”行中執行此操作:
[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'}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.