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
returnNone
用于未知密钥,而不是抛出keyrerrorTigerhawkT3和Jeremy非常感谢,它现在可以工作了。