2

I have a list like this in Python:

my_list = [
            {"id":1,"symbol":"ABC","quantity":100},
            {"id":2,"symbol":"PQR","quantity":500},
            {"id":3,"symbol":"ABC","quantity":300},
            {"id":1,"symbol":"XYZ","quantity":320},
            {"id":3,"symbol":"PQR","quantity":800},
         ]

I wanted to sum up a quantity which have similar symbols and create a new list. The new_list will look like this:

new_list = [
             { "symbol":"ABC","total_quantity":400,"ids":"1 3"}
             { "symbol":"PQR","total_quantity":1300,"ids":"2 3"}
             { "symbol":"XYZ","total_quantity":320,"ids":"1"}
           ]

I am fairly new to Python and tried some ways but not working. What can I try to achieve this?

0

4 Answers 4

1

A nice solution, is to use a defaultdict that facilitates the grouping per symbol, you just need a final step to build the ids

from collections import defaultdict

my_list = [{"id": 1, "symbol": "ABC", "quantity": 100},
           {"id": 2, "symbol": "PQR", "quantity": 500},
           {"id": 3, "symbol": "ABC", "quantity": 300},
           {"id": 1, "symbol": "XYZ", "quantity": 320},
           {"id": 3, "symbol": "PQR", "quantity": 800}, ]

expected = defaultdict(lambda: {'symbol': '', 'ids': [], "total_quantity": 0})
for row in my_list:
    expected[row['symbol']]['symbol'] = row['symbol']
    expected[row['symbol']]['ids'].append(str(row['id']))
    expected[row['symbol']]['total_quantity'] += row['quantity']

result = [{**x, 'ids': " ".join(x['ids'])} for x in expected.values()]
Sign up to request clarification or add additional context in comments.

Comments

1

if you are fine to use pandas, you can take this approach

import pandas as pd
df = pd.DataFrame.from_dict(my_list)
df1 = df.groupby('symbol').agg({'quantity':'sum',
                          'id':lambda x: ' '.join(map(str, x))}).reset_index()

Out:

{'0': {'symbol': 'ABC', 'quantity': 400, 'id': '1 3'},
 '1': {'symbol': 'PQR', 'quantity': 1300, 'id': '2 3'},
 '2': {'symbol': 'XYZ', 'quantity': 320, 'id': '1'}}

Comments

0

Something like this should work for you:

my_list = [
            {"id":1,"symbol":"ABC","quantity":100},
            {"id":2,"symbol":"PQR","quantity":500},
            {"id":3,"symbol":"ABC","quantity":300},
            {"id":1,"symbol":"XYZ","quantity":320},
            {"id":3,"symbol":"PQR","quantity":800},
         ]
new_list = []
for item in my_list:
    if item["symbol"] not in [new_item["symbol"] for new_item in new_list]:
        new_list.append({"symbol":item["symbol"],"total_quantity":item["quantity"],"ids":str(item["id"])})
    else:
        for new_item in new_list:
            if item["symbol"] == new_item["symbol"]:
                new_item["total_quantity"] += item["quantity"]
                new_item["ids"] += " "+str(item["id"])
                break
print(new_list)

Comments

0

If you prefer a core Python solution, you can do:

my_list = [
            {"id":1,"symbol":"ABC","quantity":100},
            {"id":2,"symbol":"PQR","quantity":500},
            {"id":3,"symbol":"ABC","quantity":300},
            {"id":1,"symbol":"XYZ","quantity":320},
            {"id":3,"symbol":"PQR","quantity":800},
         ]

res = []
for sym in sorted(set([x['symbol'] for x in my_list])):
    tmp = {}
    tmp['symbol'] = sym
    tmp['ids'] = r' '.join([str(x['id']) for x in my_list if x['symbol'] == sym])
    tmp['total_quantity'] = sum([x['quantity'] for x in my_list if x['symbol'] == sym])
    res.append(tmp)
       
print(res)
#[{'symbol': 'ABC', 'total_quantity': 400, 'ids': '1 3'}, 
# {'symbol': 'PQR', 'total_quantity': 1300, 'ids': '2 3'}, 
# {'symbol': 'XYZ', 'total_quantity': 320, 'ids': '1'}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.