是否可以创建字典“模板"? [英] Is it possible to create a dictionary "template"?
问题描述
我正在创建各种食谱选择器,并希望创建一个统一的字典模板.我目前有这样的东西:
I'm creating a recipe selector of sorts and am looking to create a unified dictionary template. I currently have something like this:
menu_item_var = {'name': "Menu Item", 'ing': (ingredients)}
出于时间的考虑,我担心要为每个menu_item_var
重新键入name
和ing
,并可能造成误输入.我知道我可以将Menu Item
添加为tuple,
中的项目0,并擦除dict
并运行for
循环以使字典更安全,但这不会从tuple
转换原始的menu_item_var
到dict
.有没有一种更智能"的方式来做到这一点?
I'm concerned about retyping name
and ing
for every menu_item_var
, for time's sake and the likely disaster of a mis-key. I know I could add Menu Item
as item 0 in my tuple,
erase the dict
and run a for
loop to make the dictionaries safer, but that wouldn't convert the original menu_item_var
from a tuple
to dict
. Is there a "smarter" way of doing this?
推荐答案
我可能建议您考虑创建一个类,并使用OOP代替类似的东西.
I'd probably suggest looking at creating a class and using 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" get more and more complex, it becomes more than just a data definition and requires logic. Using a Class will allow you to encapsulate this.
例如,我们的三明治上方有2个面包和2个黄油.我们可能希望在内部对此进行跟踪,如下所示:
For example, above our sandwich has 2 breads and 2 butters. We might want to keep track of this internally, like so:
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)
哪个给了我们
sandwich:
2 x butter
1 x cheese
1 x ham
2 x bread
这篇关于是否可以创建字典“模板"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!