Python - 在词典中查询词典

时间:2017-11-26 05:20:27

标签: python-3.x list dictionary nested querying

我有一个问题,是否有人会如此善良地帮助我? :)你能帮我一些关于词典中字典的代码:

一个简单的程序,提示用户输入电子邮件地址(必须存储在数据库中)才能访问该网页

这里我们将构建字典来保存数据......在一个包含整个数据库的字典中:

database_of_users = {
                "Cleaus": {"email" : "c@gmail.com"},
                "Jay" : {"email" : "j@hotmail.com"},
                "Tremaine" : {"email" : "t@gmail.com"},
                "Kyla" : {"email" : "k@outlook.com"}
              }

下一位:

user_email = input("To gain access to this feed, you must be a member
 of the site. \n\nIf you are already a member, please enter your
 email address below: \n\n").strip().lower()

然后:

while True:
 if "@gmail.com" in user_email or "@hotmail.com" in user_email or 
 "@outlook.com" in user_email:
   break

elif "@gmail.com" not in user_email or "@hotmail.com" not in 
  user_email or "@outlook.com" not in user_email:
     user_email = input("\nPlease enter a valid email
     address (gmail/hotmail/outlook): \n\n").strip().lower()

在这里,我坚持如何搜索主词典中的所有辅助(嵌套)字典值条目。我先尝试将其转换为列表,然后调用我认为是第二个字典中的值条目来查询它们,但它不起作用:

database_aslist = list(database_of_users.values()

我意识到下面的if语句只是在'项目之前调用了第一位。 =(键:值),所以在这种情况下,名称" Cleaus"," Jay"," Tremaine"," Kyla",但我只是不确定如何完全查询主词典中的所有数据,包括键和值,同时?可能吗?

if user_email in database_of_users:
   print("\nOk, I have found you. Please enjoy the show!")
   print("\n\n[GAINED ENTRY]")

if user_email not in database_of_users:
   print("\nSorry, that email address does not seem to be in our database. 
To gain access, please register for one of our packages here:
 \n\n[LINK WHERE THEY CAN SIGN UP]\n\nThank you!\n") 

提前感谢你们的帮助!

1 个答案:

答案 0 :(得分:0)

如果没有走过字典,我就不会知道。像这样:

    user_found=False
    for user in database_of_users:
        if database_of_users[user]["email"]==user_email:
             user_found=True
             break
    if user_found:
         print("\nOk, I have found you. Please enjoy the show!")
         print("\n\n[GAINED ENTRY]")
    else:
          print("\nSorry, that email address does not seem to be in our database. 
          To gain access, please register for one of our packages here:
          \n\n[LINK WHERE THEY CAN SIGN UP]\n\nThank you!\n") 

但是,如果电子邮件是输入的内容,那么在第一个嵌套中更改database_of_users以使用电子邮件可能是更容易的方法,如果这是一个选项:

    database_of_users={
         "c@gmail.com": {"name":"Cleaus"},
         "j@hotmail.com": {"name":"Jay"},
         ...
         }