I am doing my first Python program and its Hangman game. I managed to make it work but as a part of the task I need to write "best results -hall of fame" table as json file. Each entry in the table should consist of name of the person and the result they achieved (number of tries before guessing a word). My idea is to use dictionary for that purpose and to append the result of each game to that same dictionary.
My code goes like this:
with open("hall.json","a") as django:
json.dump(hall_of_fame, django)
hall_of_fame is a dictionary where after playing a game the result is saved in the form of {john:5}
The problem I have is that after playing several games my .json file looks like this:
{john:5}{ana:7}{mary:3}{jim:1}{willie:6}
instead I want to get .json file to look like this:
{john:5,ana:7,mary:3,jim:1,willie:6}
What am I doing wrong? Can someone please take a look?
CodePudding user response:
you should read your old json content. then append new item to it. an finally write it to your json file again. use code below:
with open ("hall.json") as f:
dct=json.load(f)
#add new item to dct
dct.update(hall_of_fame)
#write new dct to json file
with open("hall.json","w") as f:
json.dump(dct,f)
have fun :)
CodePudding user response:
You're overwriting the file every time you write to it. Instead, you should read the existing data from the file, append the new data to the dictionary, and then write the whole dictionary back to the file.
Here's an example of how you can do that:
import json
# Read the existing data from the file
with open("hall.json", "r") as django:
hall_of_fame = json.load(django)
# Append the new data to the dictionary
hall_of_fame["john"] = 5
hall_of_fame["ana"] = 7
hall_of_fame["mary"] = 3
hall_of_fame["jim"] = 1
hall_of_fame["willie"] = 6
# Write the updated dictionary back to the file
with open("hall.json", "w") as django:
json.dump(hall_of_fame, django)
Alternatively, you can use the json.dump()
method's ensure_ascii and indent parameters to make the resulting JSON file more readable. Here's an example:
import json
# Read the existing data from the file
with open("hall.json", "r") as django:
hall_of_fame = json.load(django)
# Append the new data to the dictionary
hall_of_fame["john"] = 5
hall_of_fame["ana"] = 7
hall_of_fame["mary"] = 3
hall_of_fame["jim"] = 1
hall_of_fame["willie"] = 6
# Write the updated dictionary back to the file
with open("hall.json", "w") as django:
json.dump(hall_of_fame, django, ensure_ascii=False, indent=4)