首页 > 解决方案 > 通过调用字典中的值获取嵌套字典中的键

问题描述

嗨,我是 python 新手,这是我的代码

如果我输入“老师”(键),则输出是 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()

标签: pythondictionary

解决方案


您可以检查字典中当前值的值,并且您知道该值也是一个字典,您可以像这样再次检查它:

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

推荐阅读