r/pythonhelp • • 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. 

3 Upvotes

10 comments sorted by