简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM