How import data from a text file into 2D list in Python?

Viewed 54

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!

2 Answers

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)

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