import json
fantasy_names = {"first": [], "middle": [], "last": []}
try:
filename = input("Enter name of file to store names: ")
while True:
for k, v in fantasy_names.items():
name = input(f"Enter {k} name: ")
v.append(name)
except KeyboardInterrupt:
with open(filename, "w") as f:
json.dump(fantasy_names, f)
Save as ‘fantasynames.py’. Run with python3 fantasynames.py. To stop entering names, press Ctrl+C.
Thanks Alexander, code works great but I don’t understand how it works Haven’t had chance to put it in a visualiser but once u do hopefully it will become clear
I have been working through the code Alexander posted and I am trying to edit it in regards to how the dictionary is saved and appended to.
What I don’t know how to do is append a value to the list in the dictionary. when I close the file, reopen it, and add names to it I am getting a new dictionary added to the file instead of it appending to the list in the original dictionary. I am assuming this is something to do with how json,dump works
This is due to the mode parameter of the open function. In the code example I posted above, the mode is w, which means (over)write. To instead append to the file, use a.
I do not think json.dump() will edit an existing JSON for you when you give it a file opened in mode "a". I guess it will just append a new JSON structure which will make the file to contain an invalid JSON (two JSON structures side by side).
The solution is:
Read the original JSON file.
Edit the structure in memory.
Use json.dump() to overwrite the original JSON file (opened in mode "w").