【问题标题】:Python - Querying dictionaries within dictionariesPython - 在字典中查询字典
【发布时间】:2017-11-26 05:20:27
【问题描述】:

我有一个问题,是否有人愿意帮助我? :) 你能帮我写一些关于字典中字典的代码吗:

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

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

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 语句只是调用 'item' = (key:value) 之前的第一位,所以在这种情况下,名称为“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") 

提前感谢大家的帮助!

【问题讨论】:

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


    【解决方案1】:

    我从来不知道不翻字典的方法。像这样的:

        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"},
             ...
             }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      • 2014-11-06
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多