List, set or Dictionary?

Hello everyone,

I am making fantasy name generator but I’m unsure of whether to use a list, set or dictionary.

What i am planning to do.

I will have three fields, first, middle and last name.

The first part of the program i want to use to populate the list, set, dictionary. It will ask me to enter a name until i break the loop.

This will happen for the first, middle and last name.

the name gen will then access the 3 fields to randomly to create the name.

Just unsure of the best way to store the names.

Oh they will be written to a file.txt then called when the name gen is run

A Dict[str, List[str]] perhaps?

fantasy_names = {
    "first": ["alice", "bob", "charlie"],
    "middle": ["a.", "b.", "c."]
    "last": ["smith", "jones", "brown"]
}

For storage, I’d recommend JSON.

Thanks Alexander, I have been reading about JSON so will try an implement that.

With the dict how would that populate with a userInput?

Something like this:

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.

could create kind of a json using defaultdict also,

from collections import defaultdict
def f():
  return defaultdict(f)
x = defaultdict(f, {'a': 1, 'b': 2})

Thanks Alexander, code works great but I don’t understand how it works :stuck_out_tongue_winking_eye: Haven’t had chance to put it in a visualiser but once u do hopefully it will become clear

Hello again,

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". :slight_smile: 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:

  1. Read the original JSON file.
  2. Edit the structure in memory.
  3. Use json.dump() to overwrite the original JSON file (opened in mode "w").
1 Like