Create multiple class instances from dictionary

Have just completed Intermediate Python and thought I would try make a basic class to count calories.
Have created a simple Food class shown below:

class Food:

def __init__(self, name, cals, grams = 100):
    self.name = name
    self.cals = cals
    self.grams = grams

I can make a class instance simply:

banana = Food(“Banana”, 105)

Now I’m hoping to make many instances of the class at once using a dictionary, for example:

food_dict = {“Banana”:105, “Oats”:389, “Milk”: 42}

I’ve tried using a for loop, but not getting the desired results. Any ideas?

How did you plan to store those objects?

I guess you could store those instances as a dictionary.

food_dict = {"Banana":105, "Oats": 389, "Milk": 42}

# dict comprehension
food_objects = { name : Food(name, food_dict[name]) for name in food_dict }

#now, food_object["Bannana"] would be an instance of the Food class

thanks jan, thats where I have landed storing the objects in a dictionary and accessing attributes using food_objects[‘Banana’].cals for example.

now planning to write a method that takes a list as an input and adds the cals, potentially adding the ability to specify grams. Thanks for your assistance