Jus*_*ahn 11 python dictionary
我正在创建各种食谱选择器,我正在寻找创建一个统一的字典模板.我目前有这样的事情:
menu_item_var = {'name': "Menu Item", 'ing': (ingredients)}
Run Code Online (Sandbox Code Playgroud)
我担心重新安排name和ing每一次menu_item_var,为了时间的缘故和可能的错误的灾难.我知道我可以Menu Item在我的tuple,擦除中添加项目0 dict并运行for循环以使字典更安全,但这不会将原始文件menu_item_var从a 转换tuple为dict.这样做有"更聪明"的方式吗?
小智 7
我可能会建议创建一个类,并使用OOP代替这样的东西.
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"))
Run Code Online (Sandbox Code Playgroud)
随着您的"模板"变得越来越复杂,它不仅仅是一个数据定义而且需要逻辑.使用类将允许您封装它.
例如,我们的三明治上面有2个面包和2个黄油.我们可能希望在内部跟踪这一点,如下所示:
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)
Run Code Online (Sandbox Code Playgroud)
这给了我们:
sandwich:
2 x butter
1 x cheese
1 x ham
2 x bread
Run Code Online (Sandbox Code Playgroud)
有几种非常简单的方法可以做到这一点。我能想到的最简单的方法是创建一个函数来返回该字典对象。
def get_menu_item(item, ingredients):
return {'name': item, 'ing': ingredients}
Run Code Online (Sandbox Code Playgroud)
就这么叫吧...
menu_item_var = get_menu_item("Menu Item", (ingredients))
Run Code Online (Sandbox Code Playgroud)
编辑:根据 PEP8 进行编辑以使用一致的代码样式。