简体   繁体   English

从字典中获取价值

[英]Get value from dictionary

it asks the user to enter a class name. 它要求用户输入一个类名。 but prints not found 但找不到打印件

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

Assuming you are searching names as opposed to classes, you could replace the for loop with 假设您正在搜索名称而不是类,则可以将for循环替换for

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

which I believe follows the hint in the comment to your question. 我相信这是根据您的问题评论中的提示进行的。

So if the value of classFind is a key in your dictionary, its value will be printed. 因此,如果classFind的值是classFind中的键,则将打印其值。 Otherwise it will print "Not found" . 否则它将打印"Not found"

myDict = {"John":["Maths261","Econ120"],"Mathew":["CSIS256","Econ120"]} 

classFind = raw_input("Enter Name to find class:") 

if classFind in myDict.keys() :
    print myDict[classFind]

else :
    print "Not Found"

If you enter someone's name you will be returned their courses. 如果输入某人的名字,您将返回他们的课程。

myDict={"John":["Maths261","Econ120"],"Mathew":["CSIS256","Econ120"]}
classfind = raw_input('enter classname : ')
for name, classes in myDict.iteritems():
    if classfind in classes:
        print name

output: 输出:

enter classname : Econ120
Mathew
John

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM