我正在嘗試為一個小專案制作一個死亡計數器并使 JSON 檔案看起來像這樣
{
"boss_name": {
"1": "Then have the time here"
"2": "same here"
"3": "ect"
"4"
"5"
}
}
但每次我嘗試過它都會像這樣覆寫:
{
"boss_name": {
"5": "03: 12: 2021: 19_59"
}
}
這是完整的代碼。我已經想到了一切,但找不到任何解決方案。我覺得它真的很容易,但真的想不出來。
while True:
boss_name = input("Are you fighting the boss from last time?"
"or is this a new boss?\n"
"(type new name to start new boss:"
"or type 'n' to use latest boss) ")
boss_name = boss_name.lower()
if boss_name == 'n':
boss_names = []
try:
for keys in deaths.keys():
boss_names.append(keys)
newy_boss = boss_names.pop()
boss_name = newy_boss
except IndexError:
print("No boss name there, please enter boss name to use")
boss_name = input("")
boss_name = boss_name.lower()
break
def counter(boss):
death_count.append('1')
deaths[boss] = {str(len(death_count)): time.strftime('%d: %m: %Y:
%H_%M')}
print(f"You have died {str(len(death_count))} times")
uj5u.com熱心網友回復:
你在這里有一個字典字典,看起來每次你用這行記錄一個新的死亡時你都在覆寫內部字典:
deaths[boss] = {str(len(death_count)): time.strftime('%d: %m: %Y: %H_%M')}
我想你想key, value在字典中創建一個新對deaths[boss],所以試試這樣的:
deaths[boss][str(len(death_count))] = time.strftime('%d: %m: %Y: %H_%M')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/373918.html
