【问题标题】:Accessing Nested Dictionary 3 levels deep Python访问嵌套字典 3 级深度 Python
【发布时间】:2022-01-24 12:46:59
【问题描述】:

在我的 for 循环成功返回我的第一组嵌套字典的键之后。我收到此错误:

for item in MENU[drink][ingredient_list]:
TypeError: 'float' object is not iterable

我需要访问所有键值对,以便对它们执行操作,但此代码卡在“espresso”。

 #3 levels deep nested dictionary
MENU = {
    "espresso": {
        "ingredients": {
            "water": 50,
            "coffee": 18,
        },
        "cost": 1.5,
    },
    "latte": {
        "ingredients": {
            "water": 200,
            "milk": 150,
            "coffee": 24,
        },
        "cost": 2.5,
    },
    "cappuccino": {
        "ingredients": {
            "water": 250,
            "milk": 100,
            "coffee": 24,
        },
        "cost": 3.0,
    }
}

#level one of the dictionary
for drink in MENU:
    #this should print the drinks and cost
    print(drink)
    #this should print the ingredients   
    for ingredient_list in MENU[drink]:
        print(ingredient_list)
        for item in MENU[drink][ingredient_list]: 
            print(item)

【问题讨论】:

  • 当您执行for ingredient_list in MENU[drink]: 时,您希望ingredient_list 在每次循环中都有什么值? (你从print(ingredient_list) 看到了什么结果?你明白为什么吗?)因此,你期望从MENU[drink][ingredient_list] 得到什么值? 每次通过外循环执行for item in... 是否有意义?
  • 请阅读ericlippert.com/2014/03/05/how-to-debug-small-programs。 print(ingredient_list) 一切都很好,看看发生了什么;但是为了从中学到一些东西,你必须看看你得到的结果,思考它们,并确保你理解它们。
  • "#this 应该打印饮料和费用" 好的,所以 - 它打印饮料,但不打印费用。是的?所以 - 给定饮料名称和整体MENU,您如何获得包含有关饮料信息的字典?鉴于该字典,您如何获得成本? (提示:这里不涉及循环;只是直接访问值。)
  • 卡尔,谢谢。我很欣赏这个链接。我得到它。我想确保我们说的是同一件事。当我提到“成本”时,我指的是在 dict MENU 的 [1]、[3] 和 [5] 处索引的名为“成本”的键:值对。我相信你明白,但只是想清楚。你在下面写了一个很酷的 sn-p,但它没有列出“成本”,它把成本放在饮料旁边。那是我完全困惑的地方。我做了我的调试 Thonny,它确实有助于了解发生了什么。尝试看看它发生了什么,但这就像 k:v 对“成本”被忽略了。
  • 我没有写剪报,为了清楚起见,我编辑了别人的答案。 “但它没有列出‘成本’,它把成本放在饮料旁边。”目前还不清楚对于这个输入,您想要的确切输出是什么。最终,您需要处理数据深度不一致这一事实。对于每个菜单项,"ingredients" 包含一个嵌套字典,但 "cost" 没有。

标签: python dictionary for-loop nested


【解决方案1】:

您也在迭代cost。试试这个:

#level one of the dictionary
for drink, data in MENU.items():
    #this should print the drinks and cost
    print(drink, data["cost"])
    #this should print the ingredients   
    for ingredient in data["ingredients"].items():
        print(ingredient)

【讨论】:

  • 谢谢。我见过 .items() 方法,但对它还不够熟悉。我现在将观看一些视频并玩弄你的代码,看看我是否能掌握它。
【解决方案2】:

正如 Bharel 所建议的,如果您只是迭代 dict MENU,默认情况下,python 只会迭代键 - 这就是如果您只运行代码就可以工作的原因:

for drink in MENU:
   #this should print the drinks and cost
   print(drink)

但是当您尝试第二个 for 循环时它会引发异常,因为您没有迭代值,要迭代值和键,请按照 Bharel 的建议使用 MENU.items()。

for key, value in MENU.items():
   #this should print the drinks and cost
   print(key, value["cost"])
   #this should print the ingredients   
   for key_i, value_i in value["ingredients"].items():
       print(key_i, value_i)

【讨论】:

    【解决方案3】:

    您的字典不是完整的 3 级。它只有 2 个完整的级别。 例如 MENU['espresso']['cost'] 等于 1.5,因此您不能对其进行迭代。

    MENU = {
        "espresso": {
            "ingredients": {
                "water": 50,
                "coffee": 18,
            },
            "cost": {
                "normal": 1.5,
                "vip": 4.5,
            }
        },
        "latte": {
            "ingredients": {
                "water": 200,
                "milk": 150,
                "coffee": 24,
            },
            "cost": {
                "normal": 2.5,
                "vip": 6.5,
            }
        },
        "cappuccino": {
            "ingredients": {
                "water": 250,
                "milk": 100,
                "coffee": 24,
            },
            "cost": {
                "normal": 3,
                "vip": 4.1,
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-28
      • 2021-01-03
      • 2017-01-20
      • 2011-04-17
      • 1970-01-01
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多