Home > Blockchain >  how to sum the quantities of dictionary items if the items are same
how to sum the quantities of dictionary items if the items are same

Time:07-29

Shopping_list= [
{"title":"cheese","quantity":50,"unit":"gm"},
{"title":"cheese","quantity":40,"unit":"gm"},
{"title":"curd","quantity":20,"unit":"gm"}
]

I want to sum the quantities only when the title matches, and then want the below output list:

final_list = [
     {"title":"cheese","quantity":90,"unit":"gm"},
     {"title":"curd","quantity":20,"unit":"gm"}]

CodePudding user response:

You could use pandas.DataFrame.groupby:

>>> import pandas as pd
>>> shopping_list = [{"title": "cheese", "quantity": 50, "unit": "gm"},
...                  {"title": "cheese", "quantity": 40, "unit": "gm"},
...                  {"title": "curd", "quantity": 20, "unit": "gm"}]
>>> pd.DataFrame(shopping_list).groupby(["title", "unit"], as_index=False).agg(sum).to_dict("records")
[{'title': 'cheese', 'quantity': 90, 'unit': 'gm'},
 {'title': 'curd', 'quantity': 20, 'unit': 'gm'}]

CodePudding user response:

You can use sort by "title" and "unit". Then group by this sorted list and calculate sum of each group.

from itertools import groupby

def key_func(k):
    return k['title'],k['unit']

Shopping_list = sorted(Shopping_list, key=key_func)
result = []
for key,value in groupby(Shopping_list, key_func):
    total = 0
    for item in list(value):
        total = item['quantity']
    result.append({'title': key[0],'quantity':total, 'unit': key[1]})

print(result)

CodePudding user response:

shopping_list= [
    {"title":"cheese","quantity":50,"unit":"gm"},
    {"title":"cheese","quantity":40,"unit":"gm"},
    {"title":"curd","quantity":20,"unit":"gm"}
]

agg = {}

for entry in shopping_list:
    if entry["title"] not in agg:
        agg[entry["title"]] = entry
    else:
        agg[entry["title"]]["quantity"]  = entry["quantity"]

final_list = list(agg.values())

CodePudding user response:

All you need to do is iterating over the Shopping_list and check the title of the dicts in the result list(with a simple linear search). If there is a dictionary with that title, increment the number of quantity otherwise that title is new and you transfer the dictionary to the result list.

Shopping_list = [
    {"title": "cheese", "quantity": 50, "unit": "gm"},
    {"title": "cheese", "quantity": 40, "unit": "gm"},
    {"title": "curd", "quantity": 20, "unit": "gm"},
]

result = []
for d1 in Shopping_list:
    for d2 in result:
        if d2["title"] == d1["title"]:
            d2["quantity"]  = d1["quantity"]
            break
    else:
        result.append(d1)

print(result)
  • Related