Search code examples
pythonlistdictionarymergefinance

Find same keys and merge in list of dicts? Python


This code produces a list of dictionaries.

 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

How do I code the following criteria:

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

So for example the result should look like:

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

Solution

    • Set up a dict (a defaultdict for convenience) to keep track of each group:
      groups = collections.defaultdict(list)
      
    • Iterate over watchlist add each x to a group:
      for x in watchlist:
          groups[(x["chain_symbol"], x["quantity"])].append(x)
      
    • Iterate over each group and sum the prices (it's the same thing as subtracting them here really):
      for group_key, group in groups.items():
          final_price = sum(x["average_price"] for x in group)
          print(group_key, final_price)