【问题标题】:How to match keys and values in a Python dictionary?如何匹配 Python 字典中的键和值?
【发布时间】:2021-01-01 19:40:55
【问题描述】:

我在一个名为“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():

有什么错误的想法吗?

提前致谢!

【问题讨论】:

  • 你为什么使用.items()users 是一个字典。它有keysget,您可以轻松地在其中查找内容。
  • 这段代码是不是刚刚从这个 S/O 站点获得的?
  • user_table= users.items() user_names = user.keys() 这里 users 是一个字典, users.items() 将返回列表并获取键列表使用“user.keys() " 不是 "user_table.keys()"
  • with中,你应该使用if '-' not in line:,因为它更具可读性

标签: python io


【解决方案1】:

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

我认为你应该做的只是使用字典users

    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')

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

【讨论】:

  • if login_status == True 应该是 if login_statusif username not in users.keys() 应该是 if username not in users
  • 对。我想我没有仔细考虑我的编辑
  • 你仍然可以改变你的答案。
【解决方案2】:

根据@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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-14
    • 2022-07-01
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多