尝试在Python中创建字典时索引超出范围

时间:2019-08-14 13:48:32

标签: python

students.csv文件包含一个化学研究生课程注册学生的列表。编写一个名为createStudentDict()的函数,该函数将打开此文件并为所有学生填充字典。密钥应该是第一列中显示的学生ID。此学生ID密钥应记录为字符串。该值应该是一个列表,其中第一项是学生的姓名(应存储为字符串),第二项是学生的年龄(整数),第三项是学生当前的全职职业(字符串) 。

这是文件的内容:

7373    Walter White    52  Teacher
8274    Skyler White    49  Author
9651    Jesse Pinkman   27  Student
2213    Saul Goodman    43  Lawyer
6666    Gus Fring   54  Chicken Guy
8787    Kim Wexler  36  Lawyer
9999    Tuco Salamanca  53  Drug Lord

我尝试编写函数并运行它?我是一名编程初学者,所以我不确定在这里放什么,除了我已经定义了使try / except块成为函数且代码未运行的功能。我不确定除索引外是否还有其他错误。

def createStudentDict():
  try:
    #Open the file    
    f=open("students.txt","r")
  except:
    #Print error message if file is not pesent
    print("File is not present")
  #Read the content of the file
  fileContent = f.read()
  #Splits the line by using the split method
  lines = fileContent.split("\n")
  #Create dictionary
  dict = {}
  #Iterate through all the line of the file

  for i in range(0,len(lines)):
    #Split line by using the comma as seperator
    detailList = lines[i].split(',')
    #Create list with the student name, age and profession
    studentDetailList = [detailList[1], int(detailList[2]), detailList[3]]
    #Add or update the item in the dictionary
    dict.update({detailList[0]:studentDetailList})
  return dict
print(createStudentDict())

例外是:

    Traceback (most recent call last):
      File "C:/Users/Owner/Documents/401 python/JONES ASSIGNMENT 3.py", line 47, in <module>
        print(createStudentDict())
      File "C:/Users/Owner/Documents/401 python/JONES ASSIGNMENT 3.py", line 37, in createStudentDict
        studentDetailList = [detailList[1], int(detailList[2]), detailList[3]]
    IndexError: list index out of range

这是我收到的错误。 这是预期的输出 像这样调用函数: 打印(createStudentDict()) 应该生成以下输出:

{'7373': ['Walter White', 52, 'Teacher'], '8274': ['Skyler White', 49, 'Author'], '9651': ['Jesse Pinkman', 27, 'Student'], '2213': ['Saul Goodman', 43, 'Lawyer'], '6666': ['Gus Fring', 54, 'Chicken Guy'], '8787': ['Kim Wexler', 36, 'Lawyer'], '9999': ['Tuco Salamanca', 53, 'Drug Lord']}

2 个答案:

答案 0 :(得分:4)

似乎CSV没有使用逗号分隔符,而是使用制表符,请尝试

 detailList = lines[i].split('\t')

由于没有逗号,您可能会得到长度为1的列表,这就是为什么会出现索引错误的原因,为了将来的实践,您可以尝试打印变量,或者更好的方法是使用像Pycharm这样的IDE并使用调试模式< / p>

编辑:为了遵守您给出的示例,我进行了以下修改:

for i in range(0,len(lines)):
    # Set the intervals to hold the same number of spaces
    line = lines[i].replace("    ", "  ")
    # Now all the spaces are double white space, split by double white space
    detailList = line.split('  ')

输出为

  

{'7373':['Walter White',52,'Teacher'],'8274':['Skyler White',49,'Author'],'9651':['Jesse Pinkman',27, '学生'],'2213':['Saul Goodman',43,'律师'],'6666':['Gus Fring',54,'鸡佬'],'8787':['Kim Wexler', 36,'Lawyer'],'9999':['Tuco Salamanca',53,'Drug Lord']}

顺便说一句,请注意,您使用名为dict的变量,而dict是python中的关键字,这是一种不良做法,可能导致某些意外行为,您可以将其重命名为{ {1}}或dict1

答案 1 :(得分:0)

可能存在格式错误的行,或者CSV标头本身破坏了循环。尝试将所有内容放入try / except子句中的for循环中,并在except内部打印该行,以便您知道它是哪一行。如果它是标题,则可以使用range(1, len(lines))忽略第一个。另外,请检查Python的内置CSV处理器模块。如果文件的格式通常不正确,则可以手动处理第一行以查看detailList = lines[i].split(',')的输出,并相应地更改格式或代码。