Search code examples
pythonfiledictionarykeykey-value

Reading a txt file into a dictionary


I have a text file like such:

Ben
5 0 0 0 0 0 0 1 0 1 -3 5 0 0 0 5 5 0 0 0 0 5 0 0 0 0 0 0 0 0 1 3 0 1 0 -5 0 0 5 5 0 5 5 5 0 5 5 0 0 0 5 5 5 5 -5 
Moose
5 5 0 0 0 0 3 0 0 1 0 5 3 0 5 0 3 3 5 0 0 0 0 0 5 0 0 0 0 0 3 5 0 0 0 0 0 5 -3 0 0 0 5 0 0 0 0 0 0 5 5 0 3 0 0 
Reuven
5 -5 0 0 0 0 -3 -5 0 1 -5 5 0 1 0 1 -3 1 -5 0 0 0 0 0 0 3 0 0 0 0 -5 1 0 1 0 -5 0 3 -3 3 0 1 5 1 0 0 0 0 0 1 3 1 5 1 3 

I need to turn this txt file into a dictionary where every other row is the key to the row after it. Example:

d = {'ben': 5 0 0 0 0 0 0 1 0 1 -3 5 0 0 0 5 5 0 0 0 0 5 0 0 0 0 0 0 0 0 1 3 0 1 0 -5 0 0 5 5 0 5 5 5 0 5 5 0 0 0 5 5 5 5 -5, 
"moose":5 5 0 0 0 0 3 0 0 1 0 5 3 0 5 0 3 3 5 0 0 0 0 0 5 0 0 0 0 0 3 5 0 0 0 0 0 5 -3 0 0 0 5 0 0 0 0 0 0 5 5 0 3 0 0, 
"Reuven":5 -5 0 0 0 0 -3 -5 0 1 -5 5 0 1 0 1 -3 1 -5 0 0 0 0 0 0 3 0 0 0 0 -5 1 0 1 0 -5 0 3 -3 3 0 1 5 1 0 0 0 0 0 1 3 1 5 1 3}

Solution

  • You can use the following way to get what you want

    How this works

    enumerate gives you a (index, value) pair for each iteration, you can directly iterate through every line in a file using the file object f. By this way at no point in time will you have to read the entire file into your memory if that concerns you.

    i % 2 == 0 indicates the line is an even line and hence will be a key in your dictionary. The else part will then use this key to add the odd number line.

    You can change line.strip().split() to just line if you dont want a list there.

    f = open('file.txt')
    
    res = {}
    
    for i, line in enumerate(f):
        if i % 2 == 0:
            key = line.strip()
        else:
            res[key] = line.strip().split()
    
    print(res)
    f.close()
    

    Output

    {'Ben': ['5', '0', '0', '0', '0', '0', '0', '1', '0', '1', '-3', '5', '0', '0', '0', '5', '5', '0', '0', '0', '0', '5', '0', '0', '0', '0', '0', '0', '0', '0', '1', '3', '0', '1', '0', '-5', '0', '0', '5', '5', '0', '5', '5', '5', '0', '5', '5', '0', '0', '0', '5', '5', '5', '5', '-5'], 'Moose': ['5', '5', '0', '0', '0', '0', '3', '0', '0', '1', '0', '5', '3', '0', '5', '0', '3', '3', '5', '0', '0', '0', '0', '0', '5', '0', '0', '0', '0', '0', '3', '5', '0', '0', '0', '0', '0', '5', '-3', '0', '0', '0', '5', '0', '0', '0', '0', '0', '0', '5', '5', '0', '3', '0', '0'], 'Reuven': ['5', '-5', '0', '0', '0', '0', '-3', '-5', '0', '1', '-5', '5', '0', '1', '0', '1', '-3', '1', '-5', '0', '0', '0', '0', '0', '0', '3', '0', '0', '0', '0', '-5', '1', '0', '1', '0', '-5', '0', '3', '-3', '3', '0', '1', '5', '1', '0', '0', '0', '0', '0', '1', '3', '1', '5', '1', '3']}