找到相同的键并合并到字典列表中? Python

Find same keys and merge in list of dicts? Python

此代码生成字典列表。

 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
  • 设置一个字典(为方便起见使用默认字典)来跟踪每个组:
    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)
    

您可以像这样在字典中存储每个符号和数量组合的所有价格值:

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)