简体   繁体   中英

How to find out if element is in any dictionary for specific key in list of dictionaries?

listofdict = [{'name':"John",'surname':"Adelo",'age':15,'adress':"1st Street 45"},{'name':"Adelo",'surname':"John",'age':25,'adress':"2nd Street 677"},...]

I want to check if there is anyone with the name John in dictionary and if there is: True, if not: False. Here is my code:

def search(name, listofdict):
    a = None
    for d in listofdict:
        if d["name"]==name:
            a = True
        else:
            a = False
    print a

However this doesn't work. If name=John it returns False, but for name=Adelo it return True. Thanks.

You need to break right after a = True .

Otherwise, a is always False when the target key is not in the last dictionary in listofdict .

By the way, this is cleaner:

def search(name, listofdict):
    for d in listofdict:
        if d["name"]==name:
            return True
    return False

Python supplies logic that helps avoids all the complications of loops. For example:

def search(name, listofdict):
    return any( d["name"]==name for d in listofdict )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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