4 回答
TA贡献1799条经验 获得超8个赞
您想要从上次运行中读取 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)
TA贡献1963条经验 获得超6个赞
我正在尝试模拟您的代码(见下文)。一切都很好。您正在读取的文件或处理源数据的方法可能有问题。
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)
结果:
defaultdict(<class 'list'>, {'p1': [{1: 2}, {1: 3}], 'p2': [{1: 2}, {1: 3}]})
TA贡献1880条经验 获得超4个赞
尝试这个
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)
所以你的结果将以这种方式存储
{"Product 1": {"12-09-2020": 1169, "13-09-2020": 1269}, ..}
您可以获取特定日期的产品价格,如下所示
product_prices_date[product_name][date]
添加回答
举报