【问题标题】:Find same keys and merge in list of dicts? Python找到相同的键并合并到字典列表中? Python
【发布时间】:2020-10-14 14:52:05
【问题描述】:

此代码生成一个字典列表。

 watchlist = r.get_open_option_positions()
    for x in watchlist:
        print('Symbol: {}, Average Price: {}, Quantity: {}'.format(x['chain_symbol'], 
    x['average_price'], x['quantity']))

输出:

Symbol: PG, Average Price: -46.5714, Quantity: 35.0000
Symbol: PG, Average Price: 33.7142, Quantity: 35.0000
Symbol: MSFT, Average Price: -80.0000, Quantity: 6.0000
Symbol: MSFT, Average Price: 53.0000, Quantity: 6.0000

如何编码以下标准:

if symbol is the same and quantity of both symbols is the same, then subtract average prices and multiply by quantity

所以例如结果应该是这样的:

Symbol: PG, Average Price: (-12.8572 * 35), Quantity: 35.000
Symbol: MSFT, Average Price: (-27 * 6), Quantity: 6.000

【问题讨论】:

  • 您是希望仅将具有此条件的连续项目分组,还是将监视列表中的所有内容分组?
  • 关注列表中的一切都会更好

标签: python list dictionary merge finance


【解决方案1】:
  • 设置一个字典(为方便起见,一个默认字典)来跟踪每个组:
    groups = collections.defaultdict(list)
    
  • 遍历watchlist 将每个x 添加到一个组中:
    for x in watchlist:
        groups[(x["chain_symbol"], x["quantity"])].append(x)
    
  • 遍历每个组并对价格求和(实际上与在此处减去它们相同):
    for group_key, group in groups.items():
        final_price = sum(x["average_price"] for x in group)
        print(group_key, final_price)
    

【讨论】:

    【解决方案2】:

    您可以将符号和数量的每个组合的所有价格值存储在字典中,如下所示:

    product = {}
    
    for x in watchlist:
        if not x['chain_symbol'], x['quantity'] in product.keys():
            product[x['chain_symbol'], x['quantity']] = []
        product[x['chain_symbol'], x['quantity']].append(x['average_price'])
    

    然后您遍历所有产品(符号和数量的组合),您可以对所有现有价格实施您想要的操作。以下代码是一个意思,但您可以将其更改为您需要的。

    for k in product.keys():
        symbol = k[0]
        quantity = k[1]
        all_the_prices = product[k]
        price = sum(all_the_prices)/len(all_the_prices) # Change here to your operation
        print('Symbol: {}, Average Price: {}, Quantity: {}'.format(symbol, price, quantity)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-20
      • 2015-08-25
      • 2019-11-19
      • 2022-12-03
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 2017-04-20
      相关资源
      最近更新 更多