循环读取学生家长CSV文件,向字典内列表追加父字典时报错求助
解决CSV加载学生家长字典时追加报错的问题
嘿,我猜你遇到的问题应该是没正确初始化字典里对应学生ID的家长列表导致的——第一次添加家长时你可能直接把单个家长字典赋值给了学生ID对应的value,而不是先创建一个列表来装它,后面再想append的时候自然就报错了(大概率是AttributeError: 'dict' object has no attribute 'append'这类错误)。
先结合你的描述还原一下可能出问题的代码片段:
import csv def parentsFile(location): parent_dict = {} with open(location) as readfile: doc = csv.DictReader(readfile, delimiter=',') # 假设你的分隔符是逗号 for row in doc: student_id = row['学生ID'] # 假设CSV里有这个字段 parent_info = {'姓名': row['家长姓名'], '邮箱': row['家长邮箱']} # 错误写法:第一次直接把单个字典赋值给键,而不是列表 if student_id not in parent_dict: parent_dict[student_id] = parent_info else: parent_dict[student_id].append(parent_info) # 这里必报错,因为value是字典不是列表
修复后的代码
我们要确保每个学生ID对应的value从一开始就是列表类型,不管是第一次添加还是后续追加:
import csv def parentsFile(location): parent_dict = {} with open(location) as readfile: doc = csv.DictReader(readfile, delimiter=',') for row in doc: student_id = row['学生ID'] parent_info = { '姓名': row['家长姓名'], '邮箱': row['家长邮箱'] } # 先检查学生ID是否在字典里 if student_id in parent_dict: # 已存在就直接追加到列表里 parent_dict[student_id].append(parent_info) else: # 不存在就新建一个列表,把第一个家长加进去 parent_dict[student_id] = [parent_info] return parent_dict
更简洁的写法(用dict.setdefault偷懒)
如果你想少写点判断,可以用字典的setdefault方法,它会自动帮我们处理不存在的键的初始化:
import csv def parentsFile(location): parent_dict = {} with open(location) as readfile: doc = csv.DictReader(readfile, delimiter=',') for row in doc: student_id = row['学生ID'] parent_info = { '姓名': row['家长姓名'], '邮箱': row['家长邮箱'] } # setdefault:如果键不存在,就把它的值设为[],然后返回这个列表,直接append就行 parent_dict.setdefault(student_id, []).append(parent_info) return parent_dict
为啥之前会报错?
简单说:第一次添加家长时,你把单个字典对象赋值给了parent_dict[student_id],这个键对应的value就成了字典,而字典根本没有append方法。当第二个同学生ID的家长出现时,你调用append自然就触发属性错误了。我们的修复方案确保每个学生ID对应的value自始至终都是列表,这样不管加第几个家长,都能正常用append追加。
内容的提问来源于stack exchange,提问作者Tristan
相关产品推荐
相关产品推荐

