如何将多个值添加到字典键

天工

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

我正在尝试将具有相应日期的产品价格存储在.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}]}

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

史蒂夫

正如@SauravPathak所说,您希望从上一次运行中读取JSON文件以在内存中重建数据结构,向其中添加当前数据集,然后将数据结构保存回文件中。这大致是您需要执行的代码:

import json
import os

output_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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章