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]
添加回答
舉報