Skip to content
Advertisement

Iterating through a list with dataclasses, and checking if an element matches the inputted int?

I”m having a bit of trouble with my code. I’m trying to get the IDs from the list and compare it to an int input. If the int is the same as the ID, it’ll print(“Yes”). If it doesn’t match an ID, it’ll print(“no”). Problem is, it’s printing no for even the numbers that should return yes to..

from dataclasses import dataclass


@dataclass
class Dog:
    ID: int
    name: str


dog_details = [
    Dog(
        ID=1,
        name="Toby"),
    Dog(
        ID=2,
        name="Rex",
    ),
    Dog(
        ID=3,
        name="Sandy",
    ),
    Dog(
        ID=4,
        name="Wanda",
    ),
    Dog(
        ID=5,
        name="Toto",
    ),
]

while True:
    for index in range(len(dog_details)):
        identification = int(input("What ID? "))
        if identification != dog_details:
            print("no")
        elif identification == dog_details:
            print("Yes")

I’m toying with variations of:


while True:
    for index in range(len(dog_details)):

        identification = int(input("What ID? "))
        if identification != dog_details:
            print("no")
        elif identification == dog_details:
            print("Yes")

Problem is, it is saying no for every number inputted.

Advertisement

Answer

dog_details is a list of Dogs; it will never be equal to an int.

What I think you might want is:

while True:
    for dog in dog_details:
        identification = int(input("What ID? "))
        if identification == dog.ID:
            print(f"Yes, this is {dog.name}")
        else:
            print(f"no, this is {dog}")

Note that because you’re asking for an ID inside the for loop, you’re comparing the ID to a specific dog in the list. (I added that dog to the print statement so that when it says “no” you can see what dog it was comparing your ID to.) If you want to compare it to all the dogs and return the matching one, do:

dogs_by_id = {dog.ID: dog for dog in dog_details}
while True:
    identification = int(input("What ID? "))
    if identification in dogs_by_id:
        print(f"Yes: {dogs_by_id[identification].name}")
    else:
        print("no")

The first line creates a dict that will allow you to look up a dog by its ID. If you were to do this without a dict, it’s more complicated; you need to loop through the entire list each time, something like:

while True:
    identification = int(input("What ID? "))
    for dog in dog_details:
        if dog.ID == identification:
            print(f"Yes: {dog.name}")
            break
    else:
        print("no")
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement