I have 2 lists of dicts with products. The first list contains dicts with products info (some basic information + stocks) The second list contains dicts with products prices. I need to merge the dictinaries based on the 'product_code' field. My lists contains 200k+ products. Is there a way to make it faster?
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
You can sort the lists in advance and if they match 1:1 you can iterate them together -
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.