如何从字典中提取同标题的Ticker与Value对生成新字典?
实现方法
思路
遍历原字典的所有索引,检查对应位置的Title是否包含指定关键词,符合条件的就将对应Ticker和Value提取出来,按顺序存入新字典。
代码示例
首先定义原数据:
data = { 'Ticker': {0: 'AKUS', 1: 'HHC', 2: 'IOVA', 3: 'DDOG'}, 'Title': {0: '10%', 1: 'Dir, 10%', 2: 'Dir', 3: 'Dir'}, 'Value': {0: '+$374,908,350', 1: '+$109,214,243', 2: '+$65,000,000', 3: '+$49,999,940'} }
然后设置目标标题关键词并生成结果:
# 指定要匹配的标题关键词 target_keyword = "10%" filtered_ticker = {} filtered_value = {} current_idx = 0 # 遍历所有索引,筛选符合条件的条目 for idx in data['Ticker']: if target_keyword in data['Title'][idx]: filtered_ticker[current_idx] = data['Ticker'][idx] filtered_value[current_idx] = data['Value'][idx] current_idx += 1 # 生成最终结果字典 result = {'Ticker': filtered_ticker, 'Value': filtered_value}
结果说明
运行上述代码后,result的输出为:
{ 'Ticker': {0: 'AKUS', 1: 'HHC'}, 'Value': {0: '+$374,908,350', 1: '+$109,214,243'} }
- 若要匹配其他标题,只需修改
target_keyword的值即可 - 同一股票如果对应多个符合条件的Title,会被多次加入结果字典
内容的提问来源于stack exchange,提问作者Gamer
相关产品推荐
相关产品推荐

