列表内的字典

问题描述 投票:1回答:3

想象一下,我有这个清单:

a=[ {"user":"John","password":"123"} , {"user":"Mike","password":"12345"} ,{"user":"Peter","password":"qwerty"}]

user=input("insert your username")
password=input("insert your password")

现在我想知道输入的用户名和密码是否在上一个列表中,我该如何解决这个问题?

如果我现在想要有3个场景:一个用户和密码匹配,第二个用户名正确但密码不正确,最后一个用户名不存在。

if {'user':user,'password':password} in a:
    print("okay")
else:
    if {'user':user} in a and {'password':password} not in a:
        print("user okay, but incorrect pass")
    else:
        print("No username")

这种类型的代码不起作用,对吧?那么我怎样才能解决第二步(在第一步之后)?

python list dictionary nested-lists
3个回答
4
投票

使用:

if {'user':user,'password':password} in a:
    # it is already in there
else:
    # it isn't in there

编辑

使用:

if {'user':user,'password':password} in a:
    # it is already in there
elif any(user == i['user'] and password != i['password'] for i in a):
    # user name is correct, but password isn't
else:
    # it isn't in there

0
投票

您可以按照@ U9-Forward建议的解决方案,或者您可以更改您的词典,而不是拥有词典列表,您可以只使用词典,其中键=实际名称和值=实际密码。如果你的dict中有很多对象并且这个函数会被频繁调用,那么这个解决方案在时间复杂度方面更好。

因此,您最初将列表a转换为名为user_password_dict的dict

user_password_dict = {user_obj['user']: user_obj['password'] for user_obj in a}

之后,您可以通过以下声明轻松检查user_password_dict中是否存在用户和相应的密码:

if user in user_password_dict and user_password_dict[user] == password:
    # do something here
else:
    # do something here

0
投票

一种方法:

a=[ {"user":"John","password":"123"} , {"user":"Mike","password":"12345"} ,{"user":"Peter","password":"qwerty"}]

user=input("insert your username")
password=input("insert your password")

flag = True
for i in a :
    if i['user'] == user and i['password'] == password :
        print('match') # or whatever
        flag = False
        break

if flag :
    print('not there ') # or whatever
© www.soinside.com 2019 - 2024. All rights reserved.