Home > Enterprise >  How to use dictionaries while creating a cookbook
How to use dictionaries while creating a cookbook

Time:11-08

I am learning Python and have thought of a project in which the user should be able to create a recipes, give the recipe a name and add the ingredients. It should be possible to create a small cookbook, so to speak.

At the moment I've this with a dictionary for each recipe, in which each ingredient is linked to a quantity.

However, I would also like to be able to add the unit of measure, e.g. gram, litre, etc. so it displays "flour = 500 gram" in the ingredients. At the moment, only "500 = flour" is displayed when I print the ingredient list.

Any idea / suggestions how I can solve this? I tried to play around with dictionaries but I couldn't find a solution.

CodePudding user response:

You can use Python f-strings to get what you want. I guess that you are using dictionary like this:

d = {
    "ingrediante1 (string)": amount (int),
    "ingrediante2 (string)": amount (int)
}

You can replace the amount integer with f-string that will contain both amount and unit of measure like this: f"{amount} {unit_of_measure}". In your case, when you are adding ingredients to a dictionary use this code instead:

# getting user input
ingredient = input("Ingredient: ")
amount = int(input("Amount: "))
unit_of_measure = input("Unit of measure: ")

# adding to a dictionary
d[ingredient] = f"{amount} {unit_of_measure}"
  • Related