字典内列表

时间:2019-03-04 03:27:56

标签: python list dictionary nested-lists

想象一下我有这个列表:

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

这种类型的代码不起作用,对吗? 那么我该如何解决第二步(在第一步之后)?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:0)

您可以按照@ U9-Forward建议的解决方案进行操作,也可以更改字典,而无需字典列表,而只需拥有一个字典,其中的键=实际名称,值=实际密码。如果您的词典中有很多对象,并且经常要调用此函数,则此方法在时间复杂度方面会更好。

因此,您最初将列表a转换为名为user_password_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