【问题标题】:python check to see if dictionary is in a listpython检查字典是否在列表中
【发布时间】:2018-02-28 09:11:13
【问题描述】:

我有一个名为 clients_list 的列表,其中包含以下字典:

    clients_list =
    [
            {'John Guy': [28, '03171992', 'Student']},
            {'Bobby Jones': [22, '02181982', 'Student']},
            {'Claire Eubanks': [18, '06291998', 'Student']},
    ]

如何使用输入的答案来检查是否有人在此列表中?我试过代码

elif answer in clients_list:
    print(f'{answer} is in our database.')

但它似乎无法正常工作。

【问题讨论】:

  • 无论如何,answer 是什么? str?您的 client_list 不是一个非常有用的数据结构......它可能应该只是一个大的 dict 对象,而不是 dict 对象中的 list。如果answer 是一个str,您想在dict 中的键上进行匹配,请使用类似any(answer in d for d in clients_list)
  • 答案是一个字符串。我想在列表中有字典,以便 client_list 中的客户端也可以通过索引来调用。有没有什么办法可以得到一个字典列表,然后通过输入客户的名字(答案)来调用特定的字典?
  • 不是没有搜索,就像我向你展示的那样。

标签: python python-3.x list dictionary


【解决方案1】:

试试这个

clients_list = [{'John Guy': [28, '03171992', 'Student']},
            {'Bobby Jones': [22, '02181982', 'Student']},
            {'Claire Eubanks': [18, '06291998', 'Student']}]

c= 'John Guy'

for item in clients_list:
    if c in item:
        print c + 'is in our database.'
        break

【讨论】:

  • 哇,好用!那么 item 是否代表列表中字典的键值?我一直认为该项目只会代表列表中的值。因此,clients_list 的值将是 {'John Guy': [28, '03171992', 'Student']} 而不仅仅是 John Guy。
【解决方案2】:

假设answer 包含"John Guy"。然后这个测试if answer in clients_list 询问字符串"John Guy" 是否在字典列表中,当然不是,因为clients_list 是字典列表,而不是字符串。现在您明白为什么您的测试没有达到您的预期吗?

这证明了 juanpa.arrivilaga 的观点,即数据结构与您正在使用的数据结构并不真正匹配。如果要查找名称,这些名称应该是字典键。类似的东西

clients_list = {
        'John Guy': [28, '03171992', 'Student'],
        'Bobby Jones': [22, '02181982', 'Student'],
        'Claire Eubanks': [18, '06291998', 'Student'],
        }

您也可以考虑将字典值命名为元组而不是列表。

【讨论】:

    【解决方案3】:

    列表元素之间的逗号。

    clients_list =[{'John Guy': [28, '03171992', 'Student']},
                {'Bobby Jones': [22, '02181982', 'Student']},
                {'Claire Eubanks': [18, '06291998', 'Student']}]
    

    至于问题,这应该可行

    for d in clients_list:
        for person in d.items():
            if "John Guy" in person[0]:
                print (person[1])
                print (person[0]+" is in our database")
    

    【讨论】:

      【解决方案4】:

      如果要在键上匹配,可以使用set().union

      clients_list = [{'John Guy': [28, '03171992', 'Student']},
                      {'Bobby Jones': [22, '02181982', 'Student']},
                      {'Claire Eubanks': [18, '06291998', 'Student']}]
      
      x = input('Enter a name:')
      
      if x in set().union(*clients_list):
          print('Name found')
      else:
          print('Name not found')
      

      【讨论】:

        【解决方案5】:

        您可以尝试使用zip 函数:

        clients_list = [{'John Guy': [28, '03171992', 'Student']}, {'Bobby Jones': [22, '02181982', 'Student']}, {'Claire Eubanks': [18, '06291998', 'Student']}]
        
        name = "John Guy"
        if name in list(zip(*clients_list))[0]:
             print(name + " is in database.")
        

        输出:

        John Guy is in database.
        

        list(zip(*clients_list)) 将返回一个列表,其中包含一个名称如下的元组:

        [('John Guy', 'Bobby Jones', 'Claire Eubanks')]
        

        然后,您所做的就是使用 [0] 获取列表中的那个元组,如果您作为输入提供的名称存在,则检查该元组。

        或者,您可以解压缩单个名称元组:

        names, = list(zip(*clients_list))
        

        并用它来检查你的名字是否在里面:

        if name in names:
             print(name + " is in database.")
        

        【讨论】:

          【解决方案6】:
          clients_list = [
                      {'John Guy': [28, '03171992', 'Student']},
                      {'Bobby Jones': [22, '02181982', 'Student']},
                      {'Claire Eubanks': [18, '06291998', 'Student']}]
          
          def get_name(answer):
              data = ("No Data Present in DB.",{'Error':'Not Found'})
              for index, val in enumerate(clients_list):
                  if answer in val.keys():
                      data =  (f'{answer} present in database & found at {index}', clients_list[index])
              return data
          
          asnwer = input("Enter a Name")
          
          found, value = get_name(asnwer)
          
          print(found, value)
          >>>Bobby Jones present in database & found at 1 {'Bobby Jones': [22, '02181982', 'Student']}
          

          【讨论】:

            猜你喜欢
            • 2018-04-10
            • 1970-01-01
            • 2017-09-28
            • 2018-12-08
            • 1970-01-01
            • 1970-01-01
            • 2014-10-06
            • 2019-02-13
            • 1970-01-01
            相关资源
            最近更新 更多