recipes = [('Peanut Butter','200g salt','500g sugar'),('Chocolate Brownie', '500g flour')]
def remove_recipe(recipe_name,recipes):
recipe_dict = dict(recipes)
size = recipe_dict.get(recipe_name)
if size is not None:
recipe_dict.pop(recipe_name)
updated_recipes = [(k, v) for k, v in recipe_dict.items()]
return updated_recipes
else:
print("There is no such recipe.")
我想达到什么目的? 您好我是 python 的新手,我正在尝试从元组列表中删除一个项目。我将食谱列表转换为字典,并将大小用于特定键的值。一旦键不是 None 它将从字典中删除该项目并将其转换回列表。
收到错误: ValueError:字典更新序列元素#0 的长度为 3;需要 2 个
我会说不需要转换为字典——假设元组的第一个元素是食谱的名称——只需使用列表理解并比较大小,:
def remove_recipe(recipe_name,recipes):
res = [r for r in recipes if r[0] != recipe_name] # filter out by the recipe name
if len(res) != len(recipes):
print("Recipe removed.")
else:
print("There is no such recipe.")
return res
字典是具有键值对的结构。所以你不能将这个元组转换为字典,因为它不知道它应该做什么。你实际上不需要字典来做你想做的事情。
recipes = [('Peanut Butter','200g salt','500g sugar'),('Chocolate Brownie', '500g flour')]
def remove_recipe(recipe_name,recipes):
for recipe in recipes:
if recipe_name in recipe:
recipes.remove(recipe)
print("Recipe removed.")
break
else:
print("There is no such recipe.")
字典可以构造你的食谱,但你必须重构你的食谱:
{
"name": 'Peanut Butter',
"ingredients": ['200g salt', '500g sugar']
}