2

I was trying to make a random generator for DND Classes and Subclasses. I tried making a text file that looks like this:

Barbarian
  Ancestral Guardian
  Battle Rager
  Beast
  Berserker
  Storm Herald
  Totem Warrior
  Wild Magic
  Zealot
Bard
  Creation
  Eloquence
  Glamour
  Lore
  Spirits
  Swords
  Valor
  Whispers

Normally I would code in the data into a list like this:

backgrounds = {}
with open("./Data/backgrounds.txt") as text:
  backgrounds = text.readlines()
text.close()

Is there anyway for it to read this data as say Barbarian Battle rager would be position (0,1) and bard glamour would be (1, 2)? Or is there a better way to format the data so it can be put into this 2D list? Thank you!

1
  • 2
    You can use JSON or YAML format to store this kind of data and directly import them into python nested structure. Commented Jul 25, 2021 at 15:25

2 Answers 2

1

First: you don't want a 2D list; you want a simple dictionary of strings to string lists.

Also, as suggested in the comments if your format is flexible, use JSON or XML rather than a flat text file. If your format is not flexible, the following will do the trick:

from pprint import pprint
from typing import Dict, List

classes: Dict[str, List[str]] = {}

with open('./Data/classes.txt') as f:
    for line in f:
        if line.startswith(' '):
            current_classes.append(line.strip())
        else:
            current_classes = classes.setdefault(line.rstrip(), [])


pprint(skills)
Sign up to request clarification or add additional context in comments.

2 Comments

It shows a more legible dictionary representation. It's only for demonstration purposes.
thanx, you should most probably add an embebded link
0

You can use JSON format to store this kind of data and directly import them into python list with the json library. I have taken the liberty to adjust your text file to a json file

backgrounds.json:

{
    "Barbarian":["Ancestral Guardian","Battle Rager","Beast","Berserker","Storm Herald","Totem Warrior","Wild Magic",""],
    "Bard":["Creation","Eloquence","Glamour","Lore","Spirits","Swords","Valor"," Whispers"]
}

The python code:

import json
with open('backgrounds.json','r') as file:
    backgrounds = json.load(file)

print(backgrounds)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.