Python读取CSV时如何匹配预定义字典值输出对应开场白?
问题根因
你的代码无法得到预期结果的核心原因有两点:
csv.reader读取到的所有单元格值默认都是字符串格式,而你定义的openingStatement字典的键是整数类型,类型不匹配无法直接索引取值- 现有print语句直接拼接了学生姓名和开场白编号字符串,没有去字典中映射对应的实际开场白文本
修正代码
只需要将读取到的开场白编号转为整数,再作为键取字典中对应的文本拼接打印即可,完整可运行代码如下:
import csv openingStatement = { 1: "this is the BEST generic opening!", 2: "this is a GOOD generic opening", 3: "this is an OKAY generic opening", 4: "this is NOT GOOD, something is going on to deserve this opening" } with open("/Users/DaveVavala/Desktop/Practice Automated Report.csv", 'r', newline='') as mainFile: reader = csv.reader(mainFile, delimiter=",") header = next(reader) for row in reader: studentName = row[0] opening_num = int(row[1]) # qualities字段当前逻辑暂未使用,可保留供后续扩展 qualities = row[2] print(f"{studentName} {openingStatement[opening_num]}")
运行输出
执行上述代码后,将得到你预期的输出结果:
Anna this is the BEST generic opening! Billy this is the BEST generic opening! Corban this is a GOOD generic opening Diane this is an OKAY generic opening Eru this is the BEST generic opening!
补充:如果后续CSV中可能出现非数字、不存在的编号值,可以在索引字典前加一层判断避免程序报错,针对你当前提供的CSV样例,上述代码可以直接正常运行。
内容的提问来源于stack exchange,提问作者davey_twelve
相关产品推荐
相关产品推荐

