Python 将字典列表中的数字添加到另一个字典列表中
假设您正在创建一个库存管理系统。Python 将字典列表中的数字添加到另一个字典列表中,python,list,dictionary,data-structures,Python,List,Dictionary,Data Structures,假设您正在创建一个库存管理系统。 我们为您提供了两个词典列表:一个表示我们目前在库存中拥有的内容(l1),另一个表示新发货的内容(l2) l1=[{“产品标识”:0,“数量”:9},{“产品标识”:1,“数量”:18},{“产品标识”:2,“数量”:22}] l2=[{“产品标识”:0,“数量”:30},{“产品标识”:1,“数量”:25},{“产品标识”:2,“数量”:25}] 我们如何将这些列表的数量加在一起,从而得到如下结果: l3=[{“产品标识”:0,“数量”:39},{“产品标识”
我们为您提供了两个词典列表:一个表示我们目前在库存中拥有的内容(l1),另一个表示新发货的内容(l2)
l1=[{“产品标识”:0,“数量”:9},{“产品标识”:1,“数量”:18},{“产品标识”:2,“数量”:22}]
l2=[{“产品标识”:0,“数量”:30},{“产品标识”:1,“数量”:25},{“产品标识”:2,“数量”:25}]
我们如何将这些列表的数量加在一起,从而得到如下结果:
l3=[{“产品标识”:0,“数量”:39},{“产品标识”:1,“数量”:43},{“产品标识”:2,“数量”:47}]
熊猫可以为这些问题提供一些惊人的解决方案。见下文:
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}]
第一例
L1和L2是所有可能的产品
如果L2没有产品,则将其插入“0”数量{“product_id”:10,“quantity”:0}
第二种情况
L2可以包含L1中不存在的新产品或顺序不同的产品
#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 ++
您可以在一行中使用列表理解添加,如下所示:
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)
有多种方法可以做到这一点,因为你是初学者,这必须是最简单的。通过循环从每个字典中获取每个键的值并添加它们
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)
你试过什么吗?同样,这必须在O(n^2)中完成。但是,如果您愿意将dict列表转换为密钥为
product\u id
的dict,那么您正在寻找一个非常简单的O(n)解决方案。它解决了您的问题吗@从product\u id
-键控dict到所需dict列表的深度空间转换也是O(n)。谢谢@IoaTzimas,这很有效!
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)