0

I am trying to do a search function for a 2 dimension array or list. How do I search thru this list and return the values of the items.

myfoodlist = [("Chicken Pasta", 10),("Beef Noodle", 12),("Hot Coffee", 4.20),( "Fish and Chips", 8.50)]

foodsearch = raw_input("Please input food to search: ")

        for item in (myfoodlist) :

            if item.find(foodsearch) != -1:
                searchReturnsItems.append(item)
        for item in searchReturnsItems:
            print(item, "\t:\t")
        searchReturnsItems.clear()

Example

I like to ask for a key word like "beef" and return a list of all beef items and store in array.

Above is my code and I have some challenges.

Anyone can provide me an example to search a 2D array will be helpful

2
  • Will each food item pair always contain food name as it's first entry? Commented Nov 17, 2019 at 11:16
  • The first item is the food menu and then price so yes. Commented Nov 17, 2019 at 12:16

2 Answers 2

1

I've slightly modified your searching method to use list comprehension, and use re package to support partial case insensitive searches.

import re

myfoodlist = [("Chicken Pasta", 10),("Beef Noodle", 12),("Hot Coffee", 4.20),( "Fish and Chips", 8.50)]

foodsearch = input("Please input food to search: ")

searchReturnsItems = [item for item in myfoodlist if re.search(foodsearch, item[0], re.IGNORECASE)]

for item in searchReturnsItems:
    print(item, "\t:\t")
searchReturnsItems.clear()

Output

Please input food to search: beef
('Beef Noodle', 12)
Sign up to request clarification or add additional context in comments.

3 Comments

You might need to use regex match to allow for partial and case insensitive matches.
if my list is now changed to a python dictionary, how will it be different?
myfoodlist = { "Beef Noodle" : 12, "Chicken Pasta" : 10, "Hot Coffee" : 4.20, "Fish and Chips" :8.50}
0
myfoodlist = [("Chicken Pasta", 10),("Beef Noodle", 12),("Hot Coffee", 4.20),( "Fish and Chips", 8.50)]

foodsearch = input("Please input food to search: ")

def searchFood():

        for item in (myfoodlist) :

            if(item[0]==foodsearch):

                return item[0],item[1]
searchFood()

output

Please input food to search: Hot Coffee

Out[2]: ('Hot Coffee', 4.2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.