Rosohatica
Rosohatica

Reputation: 13

Append dictionary in json using Python

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?

Upvotes: 0

Views: 95

Answers (1)

nariman zaeim
nariman zaeim

Reputation: 490

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 :)

Upvotes: 1

Related Questions