Nutrition problem – I don't undestand why my dict does not work

Question:

I’m trying to solve de nutrition problem in CS50 python course and I defined my dictionary as follows:

fruits = [{"Name": "Apple", "Calories": "130"},
        {"Name": "Avocado", "Calories": "50"},
        {"Name": "Banana", "Calories": "110"},
        {"Name": "Cantaloupe", "Calories": "50"},
        {"Name": "Grapefruit", "Calories": "60"},
        {"Name": "Grapes", "Calories": "90"},
        {"Name": "Honeydew", "Calories": "50"},
        {"Name": "Kiwifruit", "Calories": "90"},
        {"Name": "Lemon", "Calories": "15"},
        {"Name": "Lime", "Calories": "20"},
        {"Name": "Nectarine", "Calories": "60"},
        {"Name": "Orange", "Calories": "80"},
        {"Name": "Peach", "Calories": "60"},
        {"Name": "Pear", "Calories": "100"},
        {"Name": "Pineapple", "Calories": "50"},
        {"Name": "Plums", "Calories": "70"},
        {"Name": "Strawberries", "Calories": "50"},
        {"Name": "Sweet", "Calories": "100"},
        {"Name": "Tangerine", "Calories": "50"},
        {"Name": "Watermelon", "Calories": "80"}]

Then I ask for user input

item = str(input("Item: "))
Then loop through the dict so I can output the calories matching the fruit

for fruit in fruits:
    if fruit == item:
        print(fruit["Calories"])

My question is why this format of dict in not working. I saw solutions online and saw that it was different but my dict structure is based on the class video structure.

Asked By: jrafael

||

Answers:

You are comparing a string to a dictionary. Your list contains dictionaries. then you loop through it, and you are comparing each dictionary to your string value. What you want to check for, is the correct value inside each dictionary.

if fruit["Name"] == item:
Answered By: Proxygonn

Your item contains name of fruit. fruit in your example contains object ({"Name": "Avocado", "Calories": "50"}, for example). They can’t be equal.

Additionally, if you plan to stick with only name and calories for fruit, you could use map instead of list of maps, like so

{
  "Apple": "130", 
  "Avocado": "50", 
...}

and skip manual search and use fruits[item] to get calories

Answered By: markalex
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.