python - 从字典中获取值

标签 python dictionary

它要求用户输入类名。但找不到打印

myDict={"John":["Maths261,"Econ120"],"Mathew":["CSIS256,"Econ120"]}
    classFind=input("Enter Name to find class:")
    for key in myDict:
        if classFind in key:
            tmpVal=myDict[key]
            print(tmpVal)

        else:
            print("Not found")

最佳答案

假设您正在搜索名称而不是类,您可以将 for 循环替换为

tmpVal = myDict.get(classFind, "Not found")
print(tmpVal)

我相信这遵循了您的问题评论中的提示。

因此,如果 classFind 的值是字典中的键,则会打印其值。否则,它将打印“未找到”

关于python - 从字典中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29022142/

相关文章:

python - GCD 分数代码错误且未打印出正确答案

python - 如何从文本文件中的每一行创建一个字典条目?

ios - 为什么我的 Dictionary Item 总是返回 0? swift

python - 如何迭代和修改字典中的值?

python - 使用变量作为格式精度的麻烦

python: getfilesystemencoding() 在 shell 和 wsgi 中返回不同的值

Python 2.7 - 使用多个字典的字符串替换

python - 访问嵌套字典中的键、值

python - 有没有办法知道我的代码支持哪些版本的 python?

python - pandas 获得两列或多列的逐行最小值