-1
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

I was wondering how to read multiple lines of this sort of file into a list or dictionary as I want the ratings which are the numbers to stay with the names of the person that corresponds with the rating

Arco Bast
  • 3,595
  • 2
  • 26
  • 53

2 Answers2

0

You could read the file in pairs of two lines and populate a dictionary.

path = ... # path to your file
out = {}
with open(path) as f:
    # iterate over lines in the file
    for line in f:
        # the first, 3rd, ... line contains the name
        name = line
        # the 2nd, 4th, ... line contains the ratings
        ratings = f.next() # by calling next here, we jump two lines per iteration
        # write values to dictionary while using strip to get rid of whitespace
        out[name.strip()] = [int(rating.strip()) for rating in ratings.strip().split(' ')]

It could also be done with a while loop:

path = ... # path to your file
out = {}
with open(path) as f:
    while(True):
        # read name and ratings, which are in consecutive lines
        name = f.readline()
        ratings = f.readline()
        # stop condition: end of file is reached
        if name == '':
            break
        # write values to dictionary:
        # use name as key and convert ratings to integers. 
        # use strip to get rid of whitespace
        out[name.strip()] = [int(rating.strip()) for rating in ratings.strip().split(' ')]
Arco Bast
  • 3,595
  • 2
  • 26
  • 53
0

You can use zip to combine lines by pairs to form the dictionary

with open("file.txt","r") as f:
    lines = f.read().split("\n")
    d = { n:[*map(int,r.split())] for n,r in zip(lines[::2],lines[1::2]) }
Alain T.
  • 40,517
  • 4
  • 31
  • 51