【发布时间】:2020-05-07 06:23:58
【问题描述】:
我正在学习 cs50 ai python 课程。我试图运行涉及大 .csv 文件的代码,因此 cs50 ide 将显示消息“已终止”而不运行。它可以正常运行小 csv 文件。所以我将到目前为止的内容复制到了 Visual Studio 中。VS 会毫无问题地加载大的 csv 文件,但它给了我错误“'set' object is not subscriptable”
就在这里
a_id = names[source.lower()]["id"]
这就是名称的定义方式
# Maps names to a set of corresponding person_ids
names = {}
# Maps person_ids to a dictionary of: name, birth, movies (a set of movie_ids)
people = {}
# Maps movie_ids to a dictionary of: title, year, stars (a set of person_ids)
movies = {}
def load_data(directory):
"""
Load data from CSV files into memory.
"""
# Load people
with open(f"{directory}/people.csv", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
people[row["id"]] = {
"name": row["name"],
"birth": row["birth"],
"movies": set()
}
if row["name"].lower() not in names:
names[row["name"].lower()] = {row["id"]}
else:
names[row["name"].lower()].add(row["id"])
source:是来自用户的字符串变量。
如果我将鼠标悬停在名称上,它会显示 (name:dict)
同样的问题
films = people[a_id]["movies"]
【问题讨论】:
-
在
names[row["name"].lower()] = {row["id"]}行中,尝试删除 {row["id"]} 周围的花括号 -
总是将完整的错误消息(从单词“Traceback”开始)作为文本(不是屏幕截图)放在有问题的(不是评论)中。还有其他有用的信息。
-
您的问题与 VS 无关 - 它会在任何 IDE/编辑器中出错
-
您说您在
a_id = names[source.lower()]["id"]中遇到错误,但我在您的代码中没有看到这一行。你的信息没用。
标签: python csv dictionary search visual-studio-2017