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

Python 通过调用字典中的值获取嵌套字典中的键,python,dictionary,Python,Dictionary,您好,我是python新手,这是我的代码 如果我输入'teacher'(键),输出是类A,但我想要的是当我输入值,即像krinny一样的教师名称时,输出是类B,我如何才能做到这一点 class1 = { "class A" : {"teacher" : "simbahan", "Room" : 201 , "Schedule" : "MWF" }, "

您好,我是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()

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

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()

当我运行它时,它说TypeError:findClass()缺少2个必需的位置参数:“name”和“class1”你运行了哪一个?我做了这段代码,但我不知道发生了什么为什么什么事情class11={“class A:{“teacher”:“simbahan”,“Room”:201,“Schedule”:“MWF”},“class B:{“teacher”:“krinny”,“Room”:202,“Schedule:“TTh”}def view2():x=input(“输入教师姓名:”)def findClass(name,class1):如果class1中的i[i]['teacher']==x][0]返回class1中的i:if class1[i]['teacher']==x:return i不返回任何视图2()对不起,我是python新手,非常感谢您所做的一切不,我的意思是使用其中一个。。。检查更新的答案请复制最后一个代码段并查看是否有答案,如果您获得Indexer或删除[0]或创建一个try-except块,如果您不知道try-except,请告诉我