I would suggest that you need to look for class creation and use OOP instead for something like this.
class Recipe: def __init__(self,name,ingredients): self.name = name self.ingredients = ingredients def __str__(self): return "{name}: {ingredients}".format(name=self.name,ingredients=self.ingredients) toast = Recipe("toast",("bread")) sandwich = Recipe("sandwich",("bread","butter","ham","cheese","butter","bread"))
As your “template” is becoming more complex, it becomes more than just defining data and requires logic. Using a class will allow you to encapsulate this.
For example, over our sandwich there are 2 breads and 2 oils. We could track this internally, for example:
class Recipe: def __init__(self,name,ingredients): self.name = name self.ingredients = {} for i in ingredients: self.addIngredient(i) def addIngredient(self, ingredient): count = self.ingredients.get(ingredient,0) self.ingredients[ingredient] = count + 1 def __str__(self): out = "{name}: \n".format(name=self.name) for ingredient in self.ingredients.keys(): count = self.ingredients[ingredient] out += "\t{c} x {i}\n".format(c=count,i=ingredient) return out sandwich = Recipe("sandwich",("bread","butter","ham","cheese","butter","bread")) print str(sandwich)
What gives us:
sandwich: 2 x butter 1 x cheese 1 x ham 2 x bread
user764357
source share