Home > Software engineering >  How to check if a item is in a 2D list
How to check if a item is in a 2D list

Time:03-04

It is going to check if it's in the list, add that list to another list called checkout, and print out a receipt.

BMenu = [['Item','', 'Cost'],
        ['HamBurger', '$',38],
        ['CheeseBurger', '$', 38],
        ['Double CheeseBurger', '$', 33],
        ['Grill Chicken Sandwich', '$', 38],
        ['Crispy Chicken Sandwich', '$', 38],
        ['Spicy Chicken Sandwich', '$', 38]]

BR = input('What would you like to order?: ')
if BR in list(BMenu):
    print('In list')
else:
    print('Not on the menu')

CodePudding user response:

The way in which you've elected to structure your data is hurting you more than it's helping. I think you want a dictionary, mapping item names to their associated prices:

items = {
    "HamBuger": 38,
    "CheeseBurger": 38,
    "Double CheeseBurger": 33
    # ...
}

if input("Pick an item: ") in items:
    print("Valid")
else:
    print("Invalid")

Or possibly a list of dicts:

items = [
    {
        "name": "HamBurger",
        "price": 38
    },

    {
        "name": "CheeseBurger",
        "price": 38
    }

    #...
]

item_name = input("Pick an item: ")

if any(item["name"] == item_name for item in items):
    print("Valid")
else:
    print("Invalid")

CodePudding user response:

I assume that by "being in the list", you wanted to check whether the input string is one of the first elements of the nested list or not. If you are insisting on using list and not dict, you can try code below:

BMenu = [['Item','', 'Cost'],
        ['HamBurger', '$',38],
        ['CheeseBurger', '$', 38],
        ['Double CheeseBurger', '$', 33],
        ['Grill Chicken Sandwich', '$', 38],
        ['Crispy Chicken Sandwich', '$', 38],
        ['Spicy Chicken Sandwich', '$', 38]]
BR = input('What would you like to order?: ')
if BR in [x[0] for x in BMenu]:
  print('In list')
else:
  print('Not on the menu')

Sample input

What would you like to order?: HamBurger
In list
  • Related