繁体   English   中英

Python 匹配 2 个字典列表中的值 - 最快的解决方案

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM