[英]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']))
Output:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.