【问题标题】:dict doesn't work in visual studio (python)dict 在视觉工作室(python)中不起作用
【发布时间】: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


【解决方案1】:

试试这个

a_id = names[source.lower()]

这会将a_id 设置为ids 的集合。

在您的代码中,names 是名称和 id 之间的映射(设置类型)。所以你基本上是在尝试像{'actor': {1, 5, 3}}['actor']['id'] 这样的东西。

【讨论】:

  • 我不是想把它做成一套。我正在尝试从字典“名称”中获取一个值。
  • @tifanaser 使用 {row["id"]} 您在 names[row["name"].lower()] 中创建 set(row["id"])(不是 dict("id: row["id"])) - 并且 set() 不使用密钥,因此您不能使用 "id" 进行搜索set() 中的元素。只需使用print() 即可查看不同时刻变量中的内容。
猜你喜欢
  • 1970-01-01
  • 2019-05-15
  • 1970-01-01
  • 1970-01-01
  • 2013-08-18
  • 1970-01-01
  • 2018-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多