range() returns numbers, not the actual lines. Since you store the output of range
into lines
you won't be able to do line.split()
as line
is not the actual line, but the value from range()
. Instead, do something like this:
d = {}
with open("scores.txt") as f:
for line in f:
key, value = line.split(",")
d[key] = value
print(d)
If you need the index of the line you're on (which you never used, so I don't know if you do), you can use the enumerate
function.
d = {}
with open("scores.txt") as f:
for index, line in enumerate(f.readlines()):
key, value = line.split(",")
d[key] = value
print(d)
Mentioned in the comments, there's issues with length of the file etc. But that can be safely checked in the for loop:
d = {}
with open("scores.txt") as f:
for index, line in enumerate(f.readlines()):
if len(line.strip()) <= 0: continue
elif index == 0: continue # Skip the header or use the CSV lib
key, value = line.split(",")
d[key] = value
print(d)
To better understand this, you can lab with the range
function (if you don't like to read the docs) on a more standalone basis by doing:
for line in range(0, 10):
print(type(line), line)
Hopefully this solves your issue but also teaches what the range function does.
Lastly, consider using the csv module:
import csv
with open('scores.txt') as csvfile:
reader = csv.DictReader(csvfile, delimiter=',')
for row in reader:
print(row['name'], row['score'])
Pro's: handles empty lines, sorts everything in to a dictionary for you, skips the headers (or more accurately, puts them in as the key in the dict per row) and lastly, handles a lot of CSV "magic" for you (like special delimiters, quote chars etc)
You can use the csv lib to inline create the final result that you're after altho it's a bit slow, you'd probably better off reading and working with the data line by line unless it's for database purposes like this:
import csv
with open('scores.txt') as csvfile:
reader = csv.DictReader(csvfile, delimiter=',')
d = {row['name']:row['score'] for row in reader}