Home > Back-end >  How do I search for a value inside a 2d list in python
How do I search for a value inside a 2d list in python

Time:03-01

I am trying to create a program that searches for the exact value of the int in the first index of lists. I have to validate first the input before checking if it exists so I have this function:

fruits = [
    [1001, "Apple", "Red"],
    [1002, "Pear", "Brown"],
    [1003, "Banana", "Yellow"],
    [1004, "Grapes", "Purple"],
]


def validate_int(message):
    while True:
        try:
            intValue = int(input(message))
        except ValueError:
            print("Please enter a valid int. Try again.")
            continue
        else:
            for i in fruits:
                if intValue == i[0]:
                    print("     | ID exists. It is this fruit: ", i[1])
                    validate_int(message)
            else:
                return intValue


print("---------------------------------------")
print("Fruits")
print("---------------------------------------")
fruitID = validate_int("Enter FruitID: ")
fruitName = input("Enter FruitName: ")
fruitColor = input("Enter FruitColor: ")
new_fruit = [fruitID, fruitName, fruitColor]
fruits.append(new_fruit)

for i in fruits:
    print(i)

and when I run this code, it keeps looping and checking if the given input is int and exists, but when I append it to the list, it inputs the first input even if it's wrong, instead of the last correct input. The result looks like this:

---------------------------------------
Fruits
---------------------------------------
Enter FruitID: 1001
     | ID exists. It is this fruit:  Apple
Enter FruitID: 1005
Enter FruitName: Berries
Enter FruitColor: Pink
[1001, 'Apple', 'Red']
[1002, 'Pear', 'Brown']
[1003, 'Banana', 'Yellow']
[1004, 'Grapes', 'Purple']
[1001, 'Berries', 'Pink']

WITH THE CORRECT INPUT:

---------------------------------------
Fruits
---------------------------------------
Enter FruitID: 1234
Enter FruitName: Melon
Enter FruitColor: Orange
[1001, 'Apple', 'Red']
[1002, 'Pear', 'Brown']
[1003, 'Banana', 'Yellow']
[1004, 'Grapes', 'Purple']
[1234, 'Melon', 'Orange']

Instead of 1005 for berries, it returned 1001 even though it went through the validation. If I add the non existing ID the first time, it will append the right ID without any issues. It happens whenever I enter an existing ID for the first time. Any help would be appreciated, thank you

CodePudding user response:

You're recursively calling your function, which effectively starts the while loop again when the int is found --> infinite loop. A better data structure would be to use a dictionary for this problem.

EDIT: I saw you edited your question with desired output. You can let the function return false if it already exists and use an if statement to check function output. I adopted your way of appending new fruits:

def validate_int(message):
    while True:
        try:
            int_value = int(input(message))
        except ValueError:
            print('Please enter valid input')
        
        # loop over fruits 2d list to find fruit
        for fruit in fruits:
            if int_value == fruit[0]:
                # you can join the strings to include color
                print(f"ID exists. This is the fruit: {', '.join(fruit[1:])}")
                return False 
        return int_value
    
fruit_id = validate_int('Enter ID: ')
if fruit_id:
    fruit_name = input('Enter fruit name: ')
    fruit_color = input('Enter color: ') 
    fruits.append([fruit_id, fruit_name, fruit_color])      

for fruit in fruits:
    print(fruit)

CodePudding user response:

fruits = [
    [1001, "Apple", "Red"],
    [1002, "Pear", "Brown"],
    [1003, "Banana", "Yellow"],
    [1004, "Grapes", "Purple"],
]


def validate_int(message):
    new_value = 'NO'
    while True:
        try:
            intValue = int(input(message))
            break # if  there is no error exit the infinite loop
        except ValueError:
            print("Please enter a valid int. Try again.")
            continue
    for i in fruits:
        if intValue == i[0]:
            print("     | ID exists. It is this fruit: ", i[1])
            # remove recursive call
            # validate_int(message)
            return "VALID ID"
    return intValue


print("---------------------------------------")
print("Fruits")
print("---------------------------------------")
fruitID = validate_int("Enter FruitID: ")
if fruitID != "VALID ID":
    fruitName = input("Enter FruitName: ")
    fruitColor = input("Enter FruitColor: ")
    new_fruit = [fruitID, fruitName, fruitColor]
    fruits.append(new_fruit)

for i in fruits:
    print(i)

Test Runs:

---------------------------------------
Fruits
---------------------------------------
Enter FruitID: 1001
     | ID exists. It is this fruit:  Apple
[1001, 'Apple', 'Red']
[1002, 'Pear', 'Brown']
[1003, 'Banana', 'Yellow']
[1004, 'Grapes', 'Purple']

---------------------------------------
Fruits
---------------------------------------
Enter FruitID: 1005
Enter FruitName: Berries
Enter FruitColor: Pink
[1001, 'Apple', 'Red']
[1002, 'Pear', 'Brown']
[1003, 'Banana', 'Yellow']
[1004, 'Grapes', 'Purple']
[1005, 'Berries', 'Pink']
  • Related