[英]Python matching values in 2 list of dictinaries - fastest solution
我有 2 個帶有產品的字典列表。 第一個列表包含帶有產品信息的字典(一些基本信息+股票)第二個列表包含帶有產品價格的字典。 我需要根據“product_code”字段合並字典。 我的列表包含 200k+ 產品。 有沒有辦法讓它更快?
merged_list_of_dicts = []
for price in prices:
for stock in stocks:
if price['product_code'] == stock['product_code']:
dict_ = {}
dict_['product_code'] = price['product_code']
dict_['price'] = price['price']
dict_['stock'] = stock['stock']
all_together_list.append(dict_)
break
return all_together_list
您可以提前對列表進行排序,如果它們匹配 1:1,您可以將它們一起迭代 -
prices = sorted(prices, key = lambda x: x["product_code"])
stocks = sorted(stocks, key = lambda x: x["product_code"])
merged_list_of_dics = []
for p, s in zip(prices, stocks):
dic = {}
dic['product_code'] = price['product_code']
dic['price'] = price['price']
dic['stock'] = stock['stock']
all_together_list.append(dic)
return all_together_list
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.