【问题标题】:Python: How to access string key in dictionary from a dictionary of lists using index 0 on each list?Python:如何使用每个列表上的索引 0 从列表字典中访问字典中的字符串键?
【发布时间】:2016-04-14 18:48:57
【问题描述】:

我正在尝试遍历 dict1,它具有两个项目列表的键,即字符串。还有另一个字典 (dict2) 有四个条目。这些条目的键是 dict1 列表中仅有的四个可能的字符串。当我遍历 dict1 时,我希望程序选择列表中的第一项,然后在 dict2 中找到该键,这样我就可以根据我遍历的内容访问它们的整数值。字符串是相同的,所以如果正确访问它应该可以工作吗?这是我的代码:

hogwarts_students = { "A" : ["Gryffindor", "Slytherin"],"B" : ["Hufflepuff", "Ravenclaw"],"C" : ["Ravenclaw", "Hufflepuff"],"D" : ["Slytherin", "Ravenclaw"]}
top_choice = 0
second_choice = 0
no_choice = 0
houses = {"Gryffindor" : 0, "Hufflepuff" : 0, "Ravenclaw" : 0,
"Slytherin" : 0}
def sorting_hat(students):
    for student in hogwarts_students:
        if houses[student][0] <= len(hogwarts_students) / 4:

我是否在最后一行正确访问了与 dict1 中列表的第一项对应的整数值?还有其他更好的方法吗?

【问题讨论】:

  • 有效吗?然后就好了。
  • 您会遇到一个问题,即密钥(for 循环中的学生)可能不在您的房屋字典中。添加一些东西来检查。除此之外,如果它有效,我看不出您发布的代码有任何问题。
  • 您的循环迭代器会将学生设置为您的 hogwarts_students 字典中的键值。因此它将具有值“A”、“B”等。您将在测试中遇到键值错误,因为房屋字典没有键“A”、“B”等。

标签: python dictionary


【解决方案1】:

正如史蒂夫在他的评论中提到的,你的迭代器 student 将迭代来自 hogwarts_students 的键('A','B','C',...)。这将在您的if 语句中导致关键错误,因为它将尝试访问不存在的houses['A']

我建议同时使用.items() 来迭代hogwarts_students 的键和值,例如:

for student, house_options in hogwarts_students.items():
    first_option = house_options[0]
    if houses[first_option] <= len(hogwarts_students) // 4:
        # Do something
        pass

您还将此设置为一个接受students 参数的函数。如果students 将取代hogwarts_students,请确保您在函数中引用students 字典而不是hogwarts_students 变量。

def sorting_hat(students):
    for student, house_options in students.items():
        first_option = house_options[0]
        if houses[first_option] <= len(students) // 4:
            # Do something
            pass

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-27
    • 2019-10-20
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 2020-12-29
    • 2020-10-01
    相关资源
    最近更新 更多