i have a text file like this and i am converting the text file into a dictionary. making one of the values the key and the rest the values within the key.
JavaScript
x
4
1
0.8, 3.5, jerry, 5.5, 0, 4, 78
2
0.9, 2, amy, 6.2, 4, 4,
3
1.0, 4, alan, 7.8, 9, 90
4
and this is what i have cuz one of the student is missing a grade on purpose.
JavaScript
1
15
15
1
openData = open("students.txt", 'r')
2
3
myDic = dict()
4
5
for col in openData:
6
line = col.strip().split(",")
7
q1 = line[0]
8
q2 = line[1]
9
name = line[3]
10
mag = line[4]
11
grade = line[6]
12
myDic[name] = q1, q2, mag, grade
13
14
print(myDic)
15
my problem is when i try to run it,the output keeps saying that grade = line[6] is out of range. can someone help? Thank you
Advertisement
Answer
Check the length of line
before trying to use line[6]
JavaScript
1
12
12
1
for col in openData:
2
line = col.strip().split(",")
3
q1 = line[0]
4
q2 = line[1]
5
name = line[3]
6
mag = line[4]
7
if len(line) >= 5:
8
grade = line[6]
9
else:
10
grade = ''
11
myDic[name] = q1, q2, mag, grade
12