python - 通过调用字典中的值获取嵌套字典中的键
问题描述
嗨,我是 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()
解决方案
您可以检查字典中当前值的值,并且您知道该值也是一个字典,您可以像这样再次检查它:
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()
推荐阅读
- python - PySimpleGUI 的 sg.Combo 下拉列表中未显示的值列表?
- android - Android 上的 Google Pay 本地化
- swift - 如果一切都是以编程方式创建而不使用情节提要,如何以编程方式调整 TableView 中单元格的高度?
- php - 检查运行脚本是否在数组中
- python - 无法使用 cv2 播放整个视频
- python - 如何根据输出错误重新运行特定的 pytest 测试
- sdk - 应该使用哪个 Azure ServiceBus SDK?
- xml - 使用 bash 脚本从 XML 文件中提取特定关键字
- c++ - C++ 语句“if”被忽略
- python - 如何创建一条知道起点、终点和距离的路线