Search code examples
pythonfiledictionaryfile-read

How to read one character from a file as a key into a dictionary, then make the next n characters its value?


Lets say we have a .txt file like so (all on one line):

A2.)43@|@C3::#

So we want "A" as key for the value ".)" and "4" as key for the value "@|@" etc.. The number after the key tells us how many characters to read as the value, and the character after is the key for the next item in the dictionary.

The thing I'm struggling with is writing the loop. I'm thinking that we might want to iterate over the length of the file using a for loop. But I don't really know how to proceed.


Solution

  • This worked for me

    stringText = "A2.)43@|@C3::#"
    
    
    i=0
    myDictionary = {}
    
    
    while True:
        try:
            #First we grab the key character using i
            keyCharacter = stringText[i]
    
            #Then we grab the next character which will tell us how many characters they value will have
            # We also convert it to integer for future use
            valueLength = int(stringText[i+1])
    
            #Then we grab the value by slicing the string
            valueCharacters = stringText[i+2:i+2+valueLength]
    
            #We add this to the dictionary
            myDictionary[keyCharacter] = valueCharacters
    
            #We update i to continue where we left off
            i = i+2+valueLength
    
    
        except IndexError:
            break
    
    print myDictionary
    

    Instead of the "try and except" you could also see how long that string is and do and if statement to break the loop when i is bigger than the length of the string.