Home > Net >  Finding items in a list along with their price in Python
Finding items in a list along with their price in Python

Time:03-07

Python code to find items

Price_list = ["01", "Banana", 5.00, "unit", "02", "Mango", 20.00, "kg", 
              "03", "Apple", 15.00, "kg", "04", "Papaya", 25.00, "unit", 
              "05", "Guava", 15.00, "kg"]

print( ("Price List:"))
print( ("-----------"))
print("Item no  Item name  Price  Unit")
for i in range(0, 20, 4):
    # This is the correct one because this can access all the items in the list.
    print("{0:7} {1:9} {2:5} {3:4)".format(Price_list[i],
          Price_list[i 1], Price_list[i 2], Price_list[i 3]))

Here, I want to write a code that gives me the name and price of the fruit present in the list after asking the input i.e., name of the fruit from the user.

CodePudding user response:

This code works :-

price_list = ["01","Banana", 5.00, "unit", "02", "Mango", 20.00, "kg", "03", "Apple", 15.00, "kg", "04", "Papaya", 25.00, "unit", "05", "Guava", 15.00, "kg"]

fruit = input("Enter fruit name: ").lower().capitalize()
fruit_index = price_list.index(fruit)

print(f"{fruit} is ${price_list[fruit_index 1]} per {price_list[fruit_index 2]}")

CodePudding user response:

A flat list can work for that kind of query - you could get the index of a fruit and add/subtract to it to get its correspondig values. It may be better to wrangle your data into a better data structure/shape though:

# flat list
items = ["01","Banana", 5.00, "unit", "02", "Mango", 20.00, "kg", 
         "03", "Apple", 15.00, "kg", "04", "Papaya", 25.00, "unit", 
         "05", "Guava", 15.00, "kg"]

# order of data headers inside items
headers = ["Number","Name","Price","Unit"]

# transform your data to something you can work with
i = {items[pos 1] : dict(zip(headers, items[pos:pos 4])) 
     for pos in range(0,len(items),len(headers))}

# this will create this dictionary
# {'Banana': {'Number': '01', 'Name': 'Banana', 'Price':  5.0, 'Unit': 'unit'}, 
#  'Mango':  {'Number': '02', 'Name': 'Mango',  'Price': 20.0, 'Unit': 'kg'}, 
#  'Apple':  {'Number': '03', 'Name': 'Apple',  'Price': 15.0, 'Unit': 'kg'}, 
#  'Papaya': {'Number': '04', 'Name': 'Papaya', 'Price': 25.0, 'Unit': 'unit'}, 
#  'Guava':  {'Number': '05', 'Name': 'Guava',  'Price': 15.0, 'Unit': 'kg'}}

what = input(f"What do you want? [{(', '.join(i))}] ")

# get the item or a default result dictionary with "out" in it
w = i.get(what, {"Number":"out", "Name":what, "Price":"out", "Unit": "None"})

# print it
print(w["Name"], "=>", w["Price"])

Output:

What do you want? [Banana, Mango, Apple, Papaya, Guava] Appleees
Appleees => out

What do you want? [Banana, Mango, Apple, Papaya, Guava] Mango
Mango => 20.0
  • Related