查找相同的键并合并在字典列表中?蟒蛇

时间:2020-06-24 10:58:28

标签: python list dictionary merge finance

此代码生成词典列表。

 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

2 个答案:

答案 0 :(得分:1)

  • 设置一个dict(为方便起见,默认为dict)以跟踪每个组:
    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)
    

答案 1 :(得分:0)

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

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)