通过调用字典中的值获取嵌套字典中的键

2024-10-04 05:25:10 发布

您现在位置:Python中文网/ 问答频道 /正文

您好,我是python新手,这是我的代码

如果我输入'teacher'(键),输出是类A,但我想要的是当我输入值,即像krinny一样的教师名称时,输出是类B,我如何才能做到这一点

class1 = {
    "class A" : {"teacher" : "simbahan", "Room" : 201 , "Schedule" : "MWF" },
    "class B" : {"teacher" : "krinny", "Room" : 202 , "Schedule" : "TTh" }}

def view2():
    x = input("Enter teacher name: ")
    def findClass(name, class1):
        return next((k for k, v in class1.items() if name in v), None)

    print(findClass(x, class1))
view2()

Tags: 代码namein名称def教师classroom
1条回答
网友
1楼 · 发布于 2024-10-04 05:25:10

您可以在字典中检查当前值的值,正如您所知,该值也是一个字典,您可以像这样再次检查它:

def findClass(name, class1):
        return [i for i in class1 if class1[i]['teacher'] == x][0]

注意它将返回一个教师姓名为x的列表

有关更详细的答案:

for i in class1:
    if class1[i]['teacher'] == x:
        return i
    return None

您的最终代码是:

class1 = {
    "class A": {"teacher": "simbahan", "Room": 201, "Schedule": "MWF"},
    "class B": {"teacher": "krinny", "Room": 202, "Schedule": "TTh"}}
def view2():
    x = input("Enter teacher name: ")

    def findClass(name, class1):
        return [i for i in class1 if class1[i]['teacher'] == x][0]
    print(findClass(x, class1))
view2()

相关问题 更多 >