【问题标题】:Extracting dict keys from values从值中提取字典键
【发布时间】:2020-04-20 10:53:46
【问题描述】:
我仍在学习 python,但在从字典中提取数据时遇到了一些麻烦。我需要创建一个循环来检查每个值并提取键。所以对于这个代码,我需要找到好学生。我被困在第 3 行#blank。
我该怎么做?
提前致谢
class = {"James":"naughty", "Lisa":"nice", "Bryan":"nice"}
for student in class:
if #blank:
print("Hello, "+student+" students!")
else:
print("odd")
【问题讨论】:
标签:
dictionary
key-value-store
【解决方案1】:
使用字典方法“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 编程的对象保留的关键字