如何向字典键添加多个值

好的,我要编辑我的问题。


我试图将相应日期的产品价格存储在 .json 文件中。


我从另一个包含各种产品的 .json 文件获取数据,这些产品每天都会更新。


cache_file = get_cache(cache_file)

cache_file 是一个包含字典的列表,每个字典中都有一个产品及其详细信息。


[{"title": "Product 1", "price": 11695000, "img": "img-link", 

"link": "link-to-product", "estado_precio": "="}, {"title": "Product 2", 

"price": 8925000, "img": "img-link", "link": "link-to-product", 

"estado_precio": "="}, {"title": "Product 3", "price": 8200000, "img": "img- 

link", "link": "link-to-product", "estado_precio": "="}]

然后,我获取每个产品的详细信息,我想将价格存储在另一个具有当前日期的 .json 文件中。


product_prices_date = defaultdict(list)

for products_details in cache_file:                       

    prices_date = {}

    prices_date[fecha] = products_details['price']     

    product_prices_date[products_details['title']].append(prices_date)

            

save_to_cache(product_prices_date, cache_file)

代码存储正确,但每天都会覆盖结果


{"Product 1": [{"12-09-2020": 1169}], "Product 2": [{"12-09-2020": 8925}], "Product 3": [{"12-09-2020": 820}]}

我需要的是存储价格和日期而不覆盖


像这样的东西:


{"Product 1": [{"12-09-2020": 1169}, {"13-09-2020": 1269}], "Product 2": [{"12-09-2020": 8925}, {"13-09-2020": 8925}], "Product 3": [{"12-09-2020": 820}, {"13-09-2020": 850}]}

你能帮助我获得我想要的结果吗?问候


月关宝盒
浏览 173回答 4
4回答

守着星空守着你

您想要从上次运行中读取 JSON 文件,以在内存中重建数据结构,将当前的数据集添加到其中,然后将数据结构保存回文件中。以下是您需要执行此操作的大致代码:import jsonimport osoutput_path = '/tmp/report.json'def add_daily_vaules(file):    # Read in existing data file if it exists, else start from empty dict    if os.path.exists(output_path):        with open(output_path) as f:            product_prices_date = json.load(f)    else:        product_prices_date = {}    # Add each of today's products to the data    for products_details in file:        title = products_details['title']        price = products_details['price']        date = products_details['date']        # This is the key - you want to append to a prior entry for a specific        # title if it already exists in the data, else you want to first add        # an empty list to the data so that you can append either way        if title in product_prices_date:            prices_date = product_prices_date[title]        else:            prices_date = []            product_prices_date[title] = prices_date        prices_date.append({date:price})    # Save the structure out to the JSON file    with open(output_path, "w") as f:        json.dump(f, product_prices_date)

米脂

您必须首先从 json 文件中读取,解析它,然后附加到解析后的字典中。并再次保存到json文件。

神不在的星期二

我正在尝试模拟您的代码(见下文)。一切都很好。您正在读取的文件或处理源数据的方法可能有问题。from collections import defaultdictproduct_prices_date = defaultdict(list)prices_date = {}prices_date = {1:2}product_prices_date['p1'].append(prices_date)prices_date = {}prices_date = {1:3}product_prices_date['p1'].append(prices_date)prices_date = {}prices_date = {1:2}product_prices_date['p2'].append(prices_date)prices_date = {}prices_date = {1:3}product_prices_date['p2'].append(prices_date)print(product_prices_date)结果:defaultdict(<class 'list'>, {'p1': [{1: 2}, {1: 3}], 'p2': [{1: 2}, {1: 3}]})

慕村225694

尝试这个product_prices_date = defaultdict(dict)for products_details in file:&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; product_prices_date[product_name].update({todays_date: products_details['price']})&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;save_to_cache(product_prices_date, cache_file)所以你的结果将以这种方式存储{"Product 1": {"12-09-2020": 1169, "13-09-2020": 1269}, ..}您可以获取特定日期的产品价格,如下所示product_prices_date[product_name][date]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python