Home > OS >  how to print object data with user input
how to print object data with user input

Time:11-24

userInput = input("Enter Name: ")

class person:

    def __init__(self, name, age, job):
        self.name = name
        self.age = age
        self.job = job

People = [
    person('Josh',23,'Consultant'),
    person('Maya',25,'Accountant'),
    person('Dan',32,'Social Worker'),
    person('Keon',38,'Biomaterials Developer'),
    person('Michelle',28,'Surgeon'),
    person('Joey',34,'Lawyer')
]

so if userInput = Josh, it would print Josh's name, age, and job

‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌

CodePudding user response:

The slow method is to iterate over the list and find a match.

def find_person(people, name):
    for person in people:
        if person.name == name:
            return person
    raise ValueError("No matching person found")

This is O(n) in the size of the list, which will cause problems if your list of people is large.

But since you know in advance that you're going to be looking up people by name, you can use the person's name as a dictionary key, effectively indexing by the name rather than an integer value. So rather than creating a list of people, creating a dictionary

people = {
    'Josh': person('Josh',23,'Consultant'),
    'Maya': person('Maya',25,'Accountant'),
    'Dan': person('Dan',32,'Social Worker'),
    'Keon': person('Keon',38,'Biomaterials Developer'),
    'Michelle': person('Michelle',28,'Surgeon'),
    'Joey': person('Joey',34,'Lawyer'),
}

Then "look up a person by name" is as simple as people[name]. Of course, you'll want to hide this complexity behind a class or something and make the client-facing side look like a list, or whatever data structure you want it to look like. This approach also currently assumes that no two people will ever have the same first name, though you can work around that by having a dictionary of lists if there's a possibility of duplicates.

  • Related