简体   繁体   English

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

[英]How to add multiple values ​to a dictionary key

Okay, I'm going to edit my question.好的,我要编辑我的问题。

I am trying to store in a .json file, the prices of products with the corresponding date.我试图在 .json 文件中存储具有相应日期的产品价格。

I get the data from another .json file with various products, which are updated every day.我从另一个包含各种产品的 .json 文件中获取数据,这些产品每天都在更新。

cache_file = get_cache(cache_file)

cache_file is a list with dictionaries, and in each dictionary there is a product with its details. 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": "="}]

Then I get the details of each product, where I want to store the price in another .json file with the current date.然后我得到每个产品的详细信息,我想将价格存储在另一个 .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)

The code stores correctly, but every day it overwrites the results代码存储正确,但每天都会覆盖结果

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

What I need is to store the prices and dates without overwriting我需要的是在不覆盖的情况下存储价格和日期

something like this:像这样:

{"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}]}

Would you help me to obtain the result I seek?你会帮助我获得我所寻求的结果吗? Regards问候

As @SauravPathak says, you want to read in the JSON file from the previous run to reconstruct your data structure in memory, add the current set of data to that, and then save the data structure back out to the file.正如@SauravPathak 所说,您想从上次运行中读取 JSON 文件以在内存中重建您的数据结构,将当前数据集添加到其中,然后将数据结构保存回文件中。 Here's roughly the code you'd need to do that:这是您需要执行此操作的大致代码:

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)

You'd have to read from json file first, parse it, then append to the parsed dict.您必须首先从 json 文件中读取,解析它,然后附加到已解析的 dict 中。 And save to json file again.并再次保存到json文件。

Try this尝试这个

product_prices_date = defaultdict(dict)
for products_details in file:  
                              
    product_prices_date[product_name].update({todays_date: products_details['price']})
            
save_to_cache(product_prices_date, cache_file)

So your result will be stored in this manner所以你的结果将以这种方式存储

{"Product 1": {"12-09-2020": 1169, "13-09-2020": 1269}, ..}

and you can fetch price of product of a particular date like below您可以获取特定日期的产品价格,如下所示

product_prices_date[product_name][date]

I am trying to simulate your code (see below).我正在尝试模拟您的代码(见下文)。 And everything is ok with it.一切都很好。 Probably something wrong with a file you are reading from or with a method how you process your source data.您正在读取的文件或处理源数据的方法可能有问题。

from collections import defaultdict
product_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)

Result:结果:

defaultdict(<class 'list'>, {'p1': [{1: 2}, {1: 3}], 'p2': [{1: 2}, {1: 3}]})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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