简体   繁体   English

python检查字典是否在列表中

[英]python check to see if dictionary is in a list

I have a list called clients_list full of dictionaries such as this: 我有一个名为clients_list的字典,上面有很多这样的字典:

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

How would I check to see if someone was in this list using the input answer? 我将如何使用输入答案查看某人是否在此列表中? I have tried the code 我已经尝试过代码

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

But it does not seem to work properly. 但是它似乎无法正常工作。

Try this 尝试这个

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

Suppose answer contains "John Guy" . 假设answer包含"John Guy" Then this test if answer in clients_list asks if the string "John Guy" is in the list of dictionaries, which of course it isn't, because clients_list is a list of dictionaries, not strings. 然后进行此测试, if answer in clients_list询问字符串"John Guy"是否在词典列表中,则当然不是,因为clients_list是词典列表,而不是字符串。 Now do you see why your test doesn't do what you expect? 现在,您知道为什么您的测试没有达到您的期望了吗?

This demonstrates juanpa.arrivilaga's point that the data structure doesn't really match what you are doing with it. 这证明了juanpa.arrivilaga的观点,即数据结构与您正在使用的结构并不完全匹配。 If you want to do lookups on names, those names should be dictionary keys. 如果要对名称进行查找,则这些名称应为字典键。 Something like 就像是

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

You might also consider making the dictionary values named tuples instead of lists. 您也可以考虑将字典值命名为元组而不是列表。

If you want to match on keys, you can use set().union : 如果要匹配键,可以使用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')

Commas between the list elements. 列表元素之间的逗号。

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

As for the issue, this should work 至于问题,这应该工作

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

You can try doing it using the zip function: 您可以尝试使用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.")

Output: 输出:

John Guy is in database.

The list(zip(*clients_list)) will return a list containing a tuple with the names as such: list(zip(*clients_list))将返回一个包含元组的列表,其名称如下:

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

Then all you do is to take that one tuple of the list using [0] and check in that tuple if your the name you gave as input exists. 然后,您要做的就是使用[0]来获取列表中的那个元组,并检查该元组中是否存在您输入的名称。

Or alternatively, you can unpack the single tuple of names: 或者,您可以解压缩单个名称元组:

names, = list(zip(*clients_list))

and the use it to check if your name is in there: 并使用它来检查您的名字是否在其中:

if name in names:
     print(name + " is in database.")
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']}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM