Python ValueError报错求助:too many values to unpack (expected 3)
问题
运行测试代码时触发报错:ValueError: too many values to unpack (expected 3),相关代码如下:
BookDict 类代码
class BookDict: def __init__(self, filename): self.my_dict = {} with open(filename) as f: for line in f: title, author, ratings = line.strip().split(",") ratings = [float(rating) for rating in ratings.split(";")] self.my_dict[title] = Book(author, title, ratings) def lookup(self, title_string_some): if title_string_some in self.my_dict: book = self.my_dict[title_string_some] print(f"{book} ({book.average_rating():.2f})") return book else: print("Not Found") return None
测试代码
my_bookdict = BookDict('books2.csv') my_book = my_bookdict.lookup('Pride and Prejudice') book2 = my_bookdict.lookup('Erehwon')
问题分析与修复
核心原因
报错出现在title, author, ratings = line.strip().split(",")这一行:当books2.csv中存在带逗号的字段(比如书名"Pride and Prejudice, A Classic"),直接用split(",")会把该字段拆成多个部分,导致分割后得到的元素数量大于3,无法匹配三个变量的解包要求。
修复代码
改用Python标准库csv模块处理CSV文件,它能正确解析带引号包裹的含逗号字段,同时添加异常处理避免格式错误导致崩溃:
import csv class BookDict: def __init__(self, filename): self.my_dict = {} with open(filename, newline='', encoding='utf-8') as f: # 使用csv.reader解析文件,自动处理带引号的字段 reader = csv.reader(f) for row in reader: # 跳过格式不符的行 if len(row) != 3: print(f"跳过无效行: {row}") continue title, author, ratings_str = row try: # 转换评分为浮点型列表 ratings = [float(rating) for rating in ratings_str.split(";")] except ValueError: print(f"{title} 的评分格式错误,跳过该行") continue self.my_dict[title] = Book(author, title, ratings) def lookup(self, title_string_some): if title_string_some in self.my_dict: book = self.my_dict[title_string_some] print(f"{book} ({book.average_rating():.2f})") return book else: print("Not Found") return None
额外优化说明
csv.reader会自动识别被引号包裹的字段,不会错误分割含逗号的内容;- 添加行长度检查和评分转换异常捕获,遇到无效数据时程序不会直接崩溃,而是给出提示并跳过;
- 指定
encoding='utf-8'避免中文或特殊字符的编码问题。
内容的提问来源于stack exchange,提问作者Craig Fu
相关产品推荐
相关产品推荐

