![](/img/trans.png)
[英]How to create a dictionary with key being value of a variable in python?
[英]Create a dictionary with current_date as a key and value being how many times code run on that day Python
我需要創建一個字典列表,其中鍵是today's date
,值是代碼在today's date
運行的次數。
如果我使用一個鍵和值對創建字典列表,我創建的 for 循環正是我需要的。 如下:
# Todays's date in variable
this_day_0 = date.today()
# Format the day to be like 20200420
this_day = this_day_0.strftime("%Y%m%d")
created_today = [{"20200419": 0]
for index, time_dict in enumerate(created_today):
if this_day in time_dict.keys():
time_dict[this_day] += 1
else:
time_dict[this_day] = 1
因此,如果我今天在 4 月 20 日運行它,output 將是這樣的:
[{'20200419': 0, '20200420': 1}]
如果我再運行一次代碼,它會將 20200420 的值增加到 2。問題是我如何從created_today
的空列表開始,因為在生產中,現有的created_today
列表將被“20200419”覆蓋:0 我需要每天保存結果。 我想要的 output 將類似於以下內容:
[{'20200419': 0, '20200420': 2, '20200421': 1, '20200422': 1}] and so forth
這是一個使用json
package 對字典進行反序列化和使用文件進行持久化的解決方案
import json
from datetime import date
try:
with open('file.json', 'r') as f:
contents = f.read() or '{}'
data = json.loads(contents)
except (FileNotFoundError, json.JSONDecodeError) as e:
data = {}
key = date.today().strftime("%Y%m%d")
value = data.get(key, 0)
data[key] = value + 1
with open('file.json', 'w+') as f:
print(json.dumps(data), file=f)
您可以使用 pickle 文件來保存字典:
import pickle
this_day_0 = date.today()
this_day = this_day_0.strftime("%Y%m%d")
created_today = [{"20200419": 0}]
#load pickle to dictionary
with open('dict.pickle', 'rb') as dicto:
created_today = pickle.load(dicto)
for index, time_dict in enumerate(created_today):
if this_day in time_dict.keys():
time_dict[this_day] += 1
else:
time_dict[this_day] = 1
#save to pickle file
with open('dict.pickle', 'wb') as dicto:
pickle.dump(created_today, dicto, protocol=pickle.HIGHEST_PROTOCOL)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.