K. sweden
K. sweden

Reputation: 11

How do I search for attributes in a list of objects?

I am creating a phone register in python where the user gets the choice to add a new person to the register. I need to get the code to find if that user is already in the register. My objects have the attributes surname, firstname, phonenumber and address.

My code looks like this:

def personInRegister(surname, firstname, phonenumber, address):
    matchInRegister = False
    x = 0
    while x in range(len(people)):
        if (people[x].surname.lower == surname.lower and
            people[x].firstname.lower == firstname.lower and
            people[x].phonenumber == phonenumber and
            people[x].address.lower == address.lower):
             matchInRegister = True
             break
        else:
            x = x+1
    return matchInRegister

where people is my list of people.

I and't get it to work, and I don't know what I'm doing wrong. Please help!

Upvotes: 1

Views: 64

Answers (1)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

str.lower is a function. str.lower() calls the function and returns a lower case version of the string.

Python has a useful function for checking whether any value in a sequence is True. So we can build a sequence of boolean values like so:

def personInRegister(surname, firstname, phonenumber, address):
    return any(person.surname.lower() == surname.lower() and
               person.firstname.lower() == firstname.lower() and
               person.phonenumber == phonenumber and
               person.address.lower() == address.lower()
               for person in people)

To avoid calling lower() for the query every time through the loop you could create the query as a tuple and compare that instead:

def personInRegister(surname, firstname, phonenumber, address):
    query = (surname.lower(),
             firstname.lower(),
             phonenumber,
             address.lower())
    return any((person.surname.lower(),
                person.firstname.lower(),
                person.phonenumber,
                person.address.lower()) == query
               for person in people)

If you want to return the person you can use next:

def personInRegister(surname, firstname, phonenumber, address):
    query = (surname.lower(),
             firstname.lower(),
             phonenumber,
             address.lower())
    return next((person for person in people
                 if query == (person.surname.lower(),
                              person.firstname.lower(),
                              person.phonenumber,
                              person.address.lower())),
                None)

This will return None if it doesn't find the person. You have to use a generator expression if you don't use the default return. So this tells you the existence of a person, and gives you their record.

Upvotes: 5

Related Questions