简体   繁体   English

python 3的新手并且在访问字典值时遇到问题

[英]New to python 3 and having problems accessing dictionary values

I'm trying to make a simple login page using information stored in the dictionary.我正在尝试使用存储在字典中的信息制作一个简单的登录页面。 Everytime I enter the correct user name and password combination it falls back to the else statement- "sorry credentials not found in database".每次我输入正确的用户名和密码组合时,它都会退回到 else 语句-“抱歉,在数据库中找不到凭据”。 What am I doing wrong?我究竟做错了什么?

acc={"t":"000", "b":"123", "r":"456"}
p=input ("enter account name :")
pp=input ("enter account password :")
if p==dict.keys(acc) and pp==dict.values(acc):
 print ("access granted")
else:
 print ("sorry credentials not found in database")

The keys and values method return sequences of all keys and values, respectively. keysvalues方法分别返回所有键和值的序列。 Neither will be equal to a single key or value.两者都不等于单个键或值。

if p in acc and pp == acc[p]:
    print("access granted")
else:
    print("sorry credentials not found in database")

Tangentially, dict.keys(acc) is a rather stilted way of writing acc.keys() (and likewise for acc.values() ).切线地, dict.keys(acc)是一种相当acc.keys()的书写方式acc.keys() (对于acc.values()也是如此)。

dict.keys(acc) (same as acc.keys() ) gives you a list of all dictionary keys. dict.keys(acc) (与acc.keys()相同)为您提供所有字典键的列表。 A single login name is never equal to a list.单个登录名永远不等于列表。 What you need is to check if the login name P is in the dictionary and its value matches the stored password:您需要检查登录名P是否在字典中并且其值与存储的密码匹配:

if acc.get(P, None) == Pp:

By the way, both P and Pp are bad identifiers.顺便说一下, PPp都是坏标识符。

Examine the return value of dict.keys(acc) .检查dict.keys(acc)的返回值。

>>> acc = {"t":"000", "b":"123", "r":"456"}
>>> P = input ("enter account name : ")
Tiddles
>>> p
'Tiddles'
>>> dict.keys(acc)
dict_keys(['t', 'b', 'r'])
>>> p == dict.keys(acc)
False

It's always going to be False?它总是会是假的?

You probably want something like this:你可能想要这样的东西:

>>> acc = {"username": "Tiddles", "password": "12345"}
>>> p = input("enter account name: ")
Tiddles
>>> acc['username'] == p
True

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

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