如何匹配 Python 字典中的键和值?

时间:2021-01-01 19:40:55

标签: python io

我在名为“user_table.txt”的文本文件中有以下代表用户名和密码的数据:

Jane - valentine4Me
Billy 
Billy - slick987
Billy - monica1600Dress
 Jason - jason4evER
Brian - briguy987321CT
Laura - 100LauraSmith
   Charlotte - beutifulGIRL!
  Christoper - chrisjohn
Bruce - Bruce

然后我使用以下代码创建一个 Python 字典:

users = {}

with open("user_table.txt", 'r') as file:
    for line in file:
        line = line.strip()
    
        # if there is no password
        if ('-' in line) == False:
            continue
    
        # otherwise read into a dictionary
        else:
            key, value = line.split(' - ')
            users[key] = value
            
k= users.keys()
print(k)

以下代码是使用一些简单规则进行身份验证的函数:

a) 如果用户已登录(基于 login_status),提示

b) 如果文件中不存在用户名,则提示

c) 如果用户名存在,但与文件中的密码不匹配,则提示

这是(尝试)实现此功能的功能:

def authenticate(login_status, username, password):


    with open("user_table.txt", 'r') as file:
        for line in file:
            line = line.strip()
        
            # if there is no password
            if ('-' in line) == False:
                continue
        
            # otherwise read into a dictionary
            else:
                key, value = key, value = line.split(' - ')
                users[key] = value.strip()
                
    user_table= users.items()
    user_names = user_table.keys()
#    print(k)

    if login_status == True:
        print('User {} is already logged in.'.format(username))

    if username not in user_table.keys():
        print('username is not found')
    
    if username in user_table.keys() and password != user_table.get('value'):
        print('the password is incorrect')
        
    if username in user_table.keys() and password == user_table.get('value'):
        print('welcome to our new application')

当我调用以下内容时:

authenticate(False, 'Brian', 'briguy987321CT')

我收到此错误:

AttributeError: 'dict_items' object has no attribute 'keys'

错误原因:

if username not in user_table.keys():

知道错误在哪里吗?

提前致谢!

2 个答案:

答案 0 :(得分:1)

user_table 不是字典,而是一个类似集合的对象,它将字典中的每个条目保存为一个元组(即,{0:'a',1:'b',2:'c'}.items() 变成 dict_items([(0, 'a'), (1, 'b'), (2, 'c')])。这个对象没有 { {1}} 方法。

我认为你应该做的只是使用字典.keys()

users

(括号只是为了便于阅读)

答案 1 :(得分:0)

根据@khelwood 的建议,以下编辑解决了错误消息:

#    user_table= users.items()
#    user_names = user_table.keys()
    
#    print(k)

    if login_status == True:
        print('User {} is already logged in.'.format(username))

    if username not in users.keys():
        print('username is not found')
    
    if username in users.keys() and password != users.get('value'):
        print('the password is incorrect')
        
    if username in users.keys() and password == users.get('value'):
        print('welcome to our new application')