在目录列表中找到相同的键并合并?python

在目录列表中找到相同的键并合并?python,python,list,dictionary,merge,finance,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, Quan

此代码生成字典列表

 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
设置dict a DEFAULT dict以便于跟踪每个组:
groups = collections.defaultdict(list)
迭代观察列表将每个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)


您是希望仅将具有此条件的连续项目分组,还是将观察列表中的所有内容分组?观察列表中的所有内容都会更好检查此答案,
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)