r/pythonhelp • u/Maleficent_Oven9255 • Sep 19 '21
Creating three nested dictionaries from a text file
Hi, I’m currently trying to create three nested dictionaries from my text file (a play script) and can’t quite get the coding correct and was wondering if someone would be able to help me find where I am going wrong. My first dictionary is meant to be the acts, the second the scenes, and then the third the characters, with the values of the character dictionary being the lines of each character. I believe I have made a list for the last one, rather than a dictionary and I cannot figure out how to parse a third nested dictionary.
actDict = {}
with open ("Macbeth.txt", 'r') as inFile:
for lines in inFile:
if 'ACT' in lines:
a = lines.strip()
actKey = a.split(' ')[1]
actDict[actKey] = {}
else:
if 'SCENE' in lines:
a = lines.strip()
sceneKey = a.split(' ')[1]
actDict[actKey][sceneKey] = {}
else:
if len(actDict[actKey][sceneKey]) == 0:
if ' ' in lines:
a = lines.strip()
b = a.split('\n')
else:
a = lines.strip()
characterKey = a.split('\n')
actDict[actKey][sceneKey] = characterKey[0]
print(actDict)I have tried looking up nested dictionary examples and they format them quite differently, and more often than not end up defining the values from inside the code, rather than from a text file, and I am very new to coding so I'm having difficulty applying it to my own situation. I have tried actDict[actKey][sceneKey][characterKey] = {} and actKey[sceneKey][characterKey] = {} for my last line of code. Neither of which end up with intended results.



1
u/skellious Sep 20 '21
Hi,
this isn't perfect but hopefully it helps:
play = {}
act = None
scene = None
actor = None
with open("Macbeth.txt", 'r') as file:
for line in file:
if len(line.strip()) == 0:
continue
elif line[0:3] == "ACT":
act = line.split(" ")[1].strip()
play[act] = {}
elif line[0:5] == "SCENE":
scene = line.split(" ")[1].strip()
play[act][scene] = {}
elif " " not in line:
actor = line.strip()
else:
if actor not in play[act][scene].keys():
play[act][scene][actor] = []
play[act][scene][actor].append(line.strip())
print(play)You'll probably find it doesn't print the whole dictionary as it's quite large. Print() will probably cut it off. but the data is there.
Stage directions aren't captured well yet but you'll just need to put in some custom logic to change the "actor" to "Stage direction" or something if the line requires it.
2
1
u/skellious Sep 19 '21 edited Sep 20 '21
You make 'b' but never do anything with it. Perhaps that is one of your issues?
It's unfortunately too late at night for me to look at this in detail but if you post your script, your code and an example of the the out you WANT, not what you are getting, I can look at it tomorrow.
Make sure to post them all as formatted code blocks or share the files via a gist or similar.