2

Say you're creating an inventory management system.

You're given 2 lists of dictionaries: One representing what we currently have in inventory (l1), and the other representing what comes in with a new shipment (l2).

l1 = [{"product_id": 0, "quantity": 9}, {"product_id": 1, "quantity": 18}, {"product_id": 2, "quantity": 22}]

l2 = [{"product_id": 0, "quantity": 30}, {"product_id": 1, "quantity": 25}, {"product_id": 2, "quantity": 25}]

How would we add the quantities of these lists together so we get something like:

l3 = [{"product_id": 0, "quantity": 39}, {"product_id": 1, "quantity": 43}, {"product_id": 2, "quantity": 47}]

Pouya Esmaeili
  • 1,265
  • 4
  • 11
  • 25
league
  • 245
  • 1
  • 9
  • 3
    Did you try anything? Also, this will have to be done in O(n^2). However, if you are willing to convert from list of dicts to a dict where the key is `product_id` then you are looking at a very trivial, O(n) solution. – DeepSpace Nov 28 '20 at 19:28
  • 1
    Does it solve your problem? https://stackoverflow.com/questions/10461531/merge-and-sum-of-two-dictionaries – hidden Nov 28 '20 at 19:36
  • @DeepSpace converting from `product_id`-keyed dict back to the desired list of dicts is also O(n). – Karl Knechtel Nov 28 '20 at 19:39

4 Answers4

1

Pandas can give some amazing solutions for such problems. See below:

import pandas as pd

df1=pd.DataFrame(l1)
df2=pd.DataFrame(l2)

dfsum=pd.concat([df1, df2]).groupby('product_id').sum().reset_index()

res=dfsum.to_dict(orient='records')

>>> print(res)
[{'product_id': 0, 'quantity': 39}, {'product_id': 1, 'quantity': 43}, {'product_id': 2, 'quantity': 47}]
IoaTzimas
  • 10,538
  • 2
  • 13
  • 30
0

FIRST CASE

L1 and L2 hase all the possible product

if L2 hasnt a product it insert it with a "0" quantity {"product_id": 10, "quantity": 0}

counterOutput = 0

for Element in L1:
  L3[counterOutput]["Product_id]=Element["Product_id"]
  L3[counterOutput]["Quantity"] =Element["Quantity"]+L2[counterOutput]["Quantity"]
  counterOutput ++

SECOND CASE

L2 can contain new product not present in L1 or product in different order

#Return the quantity of a specific product(0 if product not found)
def SearchProduct(List,ProductId):
    for Element in List:
      if(ProductId == Element["Product_ID"])return Element["QUantity"]
    return 0#not fount

#Search If product exist and sum the old quantity with the new quantity to L3

counterOutput = 0
for Element in L2:
   L3[counterOutput]["Product_ID"]= Element["Product_ID"]
   L3[counterOutput]["Quantity"]= Element["Quantity"] + SearchProduct(L1,Element["Product_ID"])
   counterOutput ++

    
Nicomane
  • 11
  • 4
0

You can add by using list comprehension in one line like this:

l1 = [{"product_id": 0, "quantity": 9}, {"product_id": 1, "quantity":    18}, {"product_id": 2, "quantity": 22}]
l2 = [{"product_id": 0, "quantity": 30}, {"product_id": 1, "quantity": 25}, {"product_id": 2, "quantity": 25}]


result = []
[result.append({"product_id" : i["product_id"], "quantity" : i["quantity"] + j["quantity"]}) for i in l1 for j in l2 if i["product_id"] == j["product_id"]]
print (result)
Pouya Esmaeili
  • 1,265
  • 4
  • 11
  • 25
0

Theres multiple ways to do it, since you are the beginner this has to be the simplest. . . Get the values for each key from each dictionary via loop and add them

L3 = {}

for i in range(len(l1)):
    # get li and l2 ids
    l1ID = l1[i]['product_id']
    l2ID = l2[i]['product_id']

    # get l1 and l2 qty
    l1Qty = l1[i]['quantity']
    l2Qty = l2[i]['quantity']

    L3[i] = {"id": i, "quantity": int(l1Qty) + int(l2Qty)}

    print(L3)
huzzzus
  • 172
  • 10