I'm relatively new to python, and I'm struggling to implement a program that prompts the user for the name of a fruit (e.g. Apple) and then outputs that fruit's calories in one portion of that fruit (e.g. 130). I also want to ignore any input that isn’t a fruit. [Click here for desired output image][1]
I've tried to solve this problem using a dictionary, to match a name to its corresponding format:
fruit_dict = {
'Fruit':'Apple', 'Calories':'130',
'Fruit':'Avocado', 'Calories':'50',
'Fruit':'Banana', 'Calories':'110',
'Fruit':'Cantaloupe', 'Calories':'50',
'Fruit':'Grapefruit', 'Calories':'60',
'Fruit':'Grapes', 'Calories':'90',
'Fruit':'Honeydrew Melon', 'Calories':'50',
'Fruit':'Kiwifruit', 'Calories':'90',
'Fruit':'Lemon', 'Calories':'15',
'Fruit':'Lime', 'Calories':'20',
'Fruit':'Nectarine', 'Calories':'60',
'Fruit':'Orange', 'Calories':'80',
'Fruit':'Peach', 'Calories':'60',
'Fruit':'Pear', 'Calories':'100',
'Fruit':'Pineapple', 'Calories':'50',
'Fruit':'Plums', 'Calories':'70',
'Fruit':'Strawberries', 'Calories':'50',
'Fruit':'Sweet Cherries', 'Calories':'100',
'Fruit':'Tangerine', 'Calories':'50',
'Fruit':'Watermelon', 'Calories':'80'
}
item = input('Item: ').strip().title()
if item in fruit_dict:
print(fruit_dict.get)
Problem is, I don't know how to take a user output (e.g Apple
) and print its definition (e.g 130
)
Appreciate you reading this long description. Anyone have ideas to implement such a program?
Dictionary is the correct approach but your implementation is incorrect, I have attached the correct code below, hope that helps
fruit_dict = {
"Apple": "Calories: 130",
"Avocado": "Calories: 50",
"Banana": "Calories: 110",
"Cantaloupe": "Calories: 50",
"Grapefruit": "Calories: 60",
"Grapes": "Calories: 90",
"Honeydrew Melon": "Calories: 50",
"Kiwifruit": "Calories: 90",
"Lemon": "Calories: 15",
"Lime": "Calories: 20",
"Nectarine": "Calories: 60",
"Orange": "Calories: 80",
"Peach": "Calories: 60",
"Pear": "Calories: 100",
"Pineapple": "Calories: 50",
"Plums": "Calories: 70",
"Strawberries": "Calories: 50",
"Sweet Cherries": "Calories: 100",
"Tangerine": "Calories: 50",
"Watermelon": "Calories: 80",
}
item = input("Item: ")
print(fruit_dict.setdefault(item, "Not a fruit"))