Hans Johanbach
Hans Johanbach

Reputation: 47

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.

Upvotes: 1

Views: 55

Answers (2)

John1024
John1024

Reputation: 113834

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 )

Upvotes: 2

Dr. Jan-Philip Gehrcke
Dr. Jan-Philip Gehrcke

Reputation: 35731

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

Upvotes: 2

Related Questions