我仍在进行一个pep项目,目前处于创建自己的类和函数的阶段。我创建了一个类,可以在我的食谱库(这是字典)中找到任何给定的成分;现在我要做的就是能够将选择的配方保存到一个空字典中。这将是用户在词典中最喜欢的食谱。
我认为我理解其背后的逻辑/理论方面,但仍停留在实践上。
recipe_bank = {"reciepe1":("1", "2", "3", "4", "5"),
"reciepe2":["10 blah blah blah", "20", "30", "40", "50"]}
class ChefEasy():
def __init__(self, save):
self.save = save
def favourites(self):
my_fav = {}
for r,d in recipe_bank.items():
x = {r,d}
if choose == "y":
my_fav += x
print(my_fav)
print("Would you like to save your meal")
choose = input()
if choose == "n":
print("OK! Enjoy your meal!")
elif choose == "y":
yes = ChefEasy("y)
print(yes.save("Your meal has been saved!")
这是我的原始代码,给我-TypeError:'str'对象不可调用。
当我进一步研究这段代码时,我认为最好将{r,d}复制到对象(x)中,然后使用my_fav.update(x)方法,但是我不太确定这是否会工作。
任何帮助或建议,将不胜感激。
非常感谢:)
答案 0 :(得分:0)
我们应该在这里解决一些概念。
recipe_bank
传递到您正在创建的ChefEasy
对象中。之后,我们可以通过recipe_bank
函数从您的def favourites(self, my_fav)
中提取喜欢的食谱。 您必须修正以下错误:
yes = ChefEasy("y)
print(yes.save("Your meal has been saved!")
应该是:
yes = ChefEasy("y")
print(yes.save("Your meal has been saved!"))
我将尝试在以下几行中为您修复班级:
recipe_bank = {"reciepe1":("1", "2", "3", "4", "5"),
"reciepe2":["10 blah blah blah", "20", "30", "40", "50"]}
class ChefEasy():
def __init__(self, recipe_dict):
self.recipe_dict = recipe_dict
self.favorite_dict = {}
def favourites(self, recipe_list):
for recipe in recipe_list:
for key, value in self.recipe_dict.items():
if recipe == key:
print ('Your favourite recipe has been saved')
self.favorite_dict[key] = value
def displayfavdict(self):
print (self.favorite_dict)
myChefEasy = ChefEasy(recipe_bank)
myChefEasy.favourites(['reciepe1'])
string = input('enter recipe list here, separated by comma: ') #reciepe2
myChefEasy.favourites(string.split(','))
myChefEasy.displayfavdict()
#{'reciepe1': ('1', '2', '3', '4', '5'), 'reciepe2': ['10 blah blah blah', '20', '30', '40', '50']}
答案 1 :(得分:0)
加我的两分钱。字典具有更新方法
someDict = dict(someKey = 1, someOtherKey = 2)
empty = dict()
empty.update(someDict) # {'someKey': 1, 'someOtherKey': 2}
但是,密钥必须是唯一的,否则更新将覆盖现有密钥。如果密钥可以是列表,也可以使用默认值
someDict = dict(someKey = 1, someOtherKey = 2)
empty = dict()
for key, value in someDict.items():
empty[key] = empty.get(key, []) + [value]
print(empty) # {'someKey': [1], 'someOtherKey': [2]}
如果密钥已经存在,则最后一个方法将附加值。这可能比上面的方法更好。同样,它可用于计算与键关联的值。