字典搜索会导致Python中的关键错误



我已经查找了类似的stackoverflow问题,但没有一个像这样。简而言之,我有以下代码,试图查找用户名和相应密码的字典。如果它们匹配,然后授予访问并转到loggedin函数,否则访问被拒绝。

在下面的设置设置后,当凭据正确时,它可以很好地工作,但是在弄错了它们时,会导致关键错误:

代码

username=input("Enter username:")
                     password=input("Enter password:")
                     accessgranted=False
                     while accessgranted==False:
                         if userinfo_dict[username]==password:
                             loggedin()
                             accessgranted==True
                         else:
                             break
                     print("Sorry, wrong credentials")
                     main()

错误

   if userinfo_dict[username]==password:
KeyError: 'ee'

文件简单:

user1,pass1
user2,pass2

请有人可以a)正确并评论错误b)提出替代或更有效的方法来实现同一事物

问题是,正如许多其他人已经指出的那样,您正在尝试获得不存在的密钥的值。

一个简单的解决方法是检查仅当username是现有密钥时userinfo_dict[username] == password是否。

username = input("Enter username:")
password = input("Enter password:")
access_granted = False
while access_granted is False:
    if username in userinfo_dict.keys() and userinfo_dict[username] == password:
        loggedin()
        access_granted = True
    else:
        break
print("Sorry, wrong credentials")
main()

编辑: access_granted标志没有用,您可以做:

username = input("Enter username:")
password = input("Enter password:")
if username in userinfo_dict.keys() and userinfo_dict[username] == password:
    loggedin()
else:
    print("Sorry, wrong credentials")

您可以检查用户名和密码是否在字典中,并且它们是键值对,并具有以下内容:

#Check that both username and password in dictionary
if username in userinfo_dict.keys() and password in userinfo_dict.values():
    if userinfo_dict[username] == password:
        accessgranted = True
else:
    print('Access Denied') #Print if either username or password not in dictionary

keys()方法返回字典中的键列表,而values()方法返回字典中的值列表。

几乎总是使用dictionary.get(key)而不是dictionary[key]。当键不存在时(例如在这种情况下)是安全的,而后者会出现错误。

if userinfo_dict.get(username) == password: # returns None is key doesn't exist
    loggedin()
    accessGranted=True
else:
    break

错误告诉您您已经输入了用户名的值" ee",但是没有名为" ee"的用户(也没有键值配对用字典中的键" ee")。这是尝试获得不存在的密钥值的预期结果。

正确的python习惯用于测试钥匙的存在是:

if user_name in userinfo_dict:

i与上述同意。问题在于获取不存在的密钥。尝试一下:

  • 通过try/除了块,
  • 通过字典get()方法。

此外,代码需要一些重构,例如:

  • 通过'is'a;
  • 检查false
  • accessgranted == true应该是分配的,而不是比较;
  • 循环的逻辑也必须更改。

请参阅下文:

username = input("Enter username:")
password = input("Enter password:")
access_granted = False
while access_granted is False:
    if userinfo_dict.get(username) == password:
        # loggedin()
        access_granted = True
    else:
        print("Sorry, wrong credentials")
        break
# main()

最新更新