Cizhu
Cizhu

Reputation: 35

Index Position in a 2D list to get a sub return value from same list

So basically atm i've made two different lists, and their places are respective of each other. User inputs an item name. The program searches for its index in the pre-defined list and then gives its respective value from the second list.

What i want is the list on the first comment (2d list) to work. Is it possible that using that list, a user inputs : 'Bread'.

The program gets its index and then returns the value 5. Basically indexing in 2d list.I've searched a lot but to no avail.

If you could provide a code or atleast guide me the right way.

Thanks.

#super_market_prices=[['Bread',5],['Loaf',100],['Meat_Chicken',2.4],['Meat_Cow',450]]
'''
Program listing Super Market Prices
Search by name and get the price
'''
super_market_items=['Bread','Loaf','Meat_Chicken','Meat_Cow']
super_market_prices=[5,4,20,40]

item=str(input('Enter item name: '))
Final_item=item.capitalize()                    #Even if the user inputs lower_case
                                                #the program Capitalizes first letter
try:
    Place=super_market_items.index(Final_item)
    print(super_market_prices[Place])
except ValueError:
    print('Item not in list.')

Upvotes: 3

Views: 75

Answers (3)

Sheldore
Sheldore

Reputation: 39072

This is another work around to your problem. P.S: I used @user3483203's suggestion to use item.title() instead of item.capitalize() as the latter was resulting in error for the string with an underscore. Here I am making use of the fact that each item is succeeded by its price. Hence index+1

super_market_prices=np.array([['Bread',5],['Loaf',100],['Meat_Chicken',2.4],['Meat_Cow',450]]).ravel()

item=str(input('Enter item name: '))
Final_item=item.title()      

try:
    index = np.where(super_market_prices == Final_item)[0] 
    print (float(super_market_prices[index+1][0]))
except ValueError:
    print('Item not in list.')

Upvotes: 1

user3483203
user3483203

Reputation: 51165

You don't want a 2D list, you want a dictionary, and luckily, it's super simple to go from a 2D list (where each sublist has only two elements) to a dictionary:

prices = [['Bread',5],['Loaf',100],['Meat_Chicken',2.4],['Meat_Cow',450]]
d = dict(prices)
# {'Bread': 5, 'Loaf': 100, 'Meat_Chicken': 2.4, 'Meat_Cow': 450}

Now all you have to do is query the dictionary (O(1) lookup):

>>> d['Bread']
5

If you want to enable error checking:

>>> d.get('Bread', 'Item not found')
5
>>> d.get('Toast', 'Item not found')
'Item not found'

Upvotes: 4

rafaelc
rafaelc

Reputation: 59284

You can easily go from your "2d-list" from those two separate sequences by using zip

super_market_prices=[['Bread',5],['Loaf',100],['Meat_Chicken',2.4],['Meat_Cow',450]]

l1, l2 = zip(*super_market_prices)

>>> print(l1)
('Bread', 'Loaf', 'Meat_Chicken', 'Meat_Cow')
>>> print(l2)
(5, 100, 2.4, 450)

and just keep your code as is.

Upvotes: 1

Related Questions