Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用if语句验证字典成员身份_Python_Dictionary - Fatal编程技术网

Python 使用if语句验证字典成员身份

Python 使用if语句验证字典成员身份,python,dictionary,Python,Dictionary,我编写此代码是为了验证用户提供的值和键是否与我的dict中的值和键匹配。当它们匹配时,代码的欢迎部分将运行,但如果其中一个错误,则必须运行else语句 name = input("Name: ") code = input("Code: ") users = {'rafiki':'12345', 'wanjiru':'12334', 'madalitso':'taxpos'} if _______ in users: #at this point is where i need your s

我编写此代码是为了验证用户提供的值和键是否与我的
dict
中的值和键匹配。当它们匹配时,代码的欢迎部分将运行,但如果其中一个错误,则必须运行
else
语句

name = input("Name: ")
code = input("Code: ")

users = {'rafiki':'12345', 'wanjiru':'12334', 'madalitso':'taxpos'}

if _______ in users: #at this point is where i need your support, yoverify both key and its value at once.
    print ("Welcome back %s " % username)

else:
    print ("Please check if your name or Code are correctly spelled")
使用以下命令:

if name in users and users[name] == code:
    print "Welcome back %s" % username
这应该起作用:

if name in users and code == users[name]:
在一次操作中:

if users.get(name) == code:

因为
dict.get
return
None
用于未知密钥,而不是抛出
keyrerror

TigerhawkT3和Jeremy非常感谢,它现在可以工作了。