首页 > 解决方案 > 从值中提取字典键

问题描述

我仍在学习 python,我在从字典中提取数据时遇到了一些麻烦。我需要创建一个循环来检查每个值并提取键。所以对于这个代码,我需要找到好学生。我被困在第 3 行#blank。我该怎么做?提前致谢

class = {"James":"naughty", "Lisa":"nice", "Bryan":"nice"}
for student in class:
    if #blank:
        print("Hello, "+student+" students!")
else:
    print("odd")

标签: dictionarykey-value-store

解决方案


使用字典方法“keys(), values(), items()”:

def get_students_by_criteria(student_class, criteria):

    students = []

    for candidate, value in student_class.items():
        if value == criteria:
            students.append(candidate)

    return students

my_class = {"James":"naughty", "Lisa":"nice", "Bryan":"nice"}


print(get_students_by_criteria(my_class, "nice"))

警告“类”这个词,它是为面向 Python 编程的对象保留的关键字


推荐阅读