Skip to content
Advertisement

converting a text in a dictionary

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.

0.8, 3.5, jerry, 5.5, 0, 4, 78
0.9, 2, amy, 6.2, 4, 4, 
1.0, 4, alan, 7.8, 9, 90

and this is what i have cuz one of the student is missing a grade on purpose.

  openData = open("students.txt", 'r')

  myDic = dict()

  for col in openData:
      line = col.strip().split(",")
      q1 = line[0]
      q2 = line[1]
      name = line[3]  
      mag = line[4]
      grade = line[6]
      myDic[name] = q1, q2, mag, grade

   print(myDic)

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]

for col in openData:
    line = col.strip().split(",")
    q1 = line[0]
    q2 = line[1]
    name = line[3]  
    mag = line[4]
    if len(line) >= 5:
        grade = line[6]
    else:
        grade = ''
    myDic[name] = q1, q2, mag, grade
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement