开始使用免费开始使用

遍历字典

您的配方缩放器已经成型!您有一个名为 recipe 的字典,其中键是配料名称,值是以克为单位的用量,用于制作番茄罗勒意面。现在,您需要将所有用量按 2 倍缩放,以便招待更多派对来宾。您将遍历字典的各项并计算缩放后的用量。

本练习是课程的一部分

Python for Developers 入门

查看课程

练习说明

  • 使用 for 循环遍历 recipe 字典,迭代变量使用 ingredientqty
  • 在循环内,创建名为 scaled_qty 的变量,将原始用量乘以 2 的缩放因子。

交互式实操练习

通过完成这段示例代码来试试这个练习。

recipe = {
    "fusilli": 500,
    "tomatoes": 400,
    "basil": 20,
    "garlic": 15,
    "olive oil": 15,
    "salt": 7
}

# Loop through the recipe dictionary items
for ____, ____ in recipe.____:
    # Calculate the scaled quantity by multiplying by 2
    scaled_qty = qty ____
    
    print(ingredient, ":", scaled_qty, "g")
编辑并运行代码