代码之家  ›  专栏  ›  技术社区  ›  Genkuru

如何遍历字典以获得最低级别的值?

  •  2
  • Genkuru  · 技术社区  · 1 年前

    请帮助我了解如何为每种产品提取每种成分的价值,并用它做些什么。但对于初学者来说,我只想一个接一个地打印出来。

    MENU = {
        "product_1": {
            "ingredients": {
                "ingredient_1": 50,
                "ingredient_2": 18
            },
            "cost": 1.5
        },
        "product_2": {
            "ingredients": {
                "ingredient_1": 200,
                "ingredient_2": 150,
                "ingredient_3": 24
            },
            "cost": 2.5
        }
    }
    

    我从这个代码开始:

    for ingredient in MENU:
       print(MENU["product_2"]["ingredients"])
    

    但这将所有3种成分及其对product_2的值打印出3次。我需要它打印出200、150、24

    2 回复  |  直到 1 年前
        1
  •  1
  •   mkrieger1 djuarezg    1 年前

    正如@John所评论的:

    你需要熟悉 dictionary :

    for key,value in MENU["product_2"]["ingredients"].items():
      print(value)
    

    for x in MENU["product_2"]["ingredients"].values():
      print(x)
    

    输出

    200
    150
    24
    

    如果您只需要一个列表:

    list(MENU["product_2"]["ingredients"].values())
    #[200, 150, 24]
    
        2
  •  1
  •   tymerius    1 年前

    如果需要所有值,请将它们作为层次结构进行迭代。

    for products in MENU:
        for key,value in MENU[products]["ingredients"].items():
            print(value)
    

    Check out this explanation about dictionaries in python with examples

        3
  •  1
  •   mkrieger1 djuarezg    1 年前

    您需要从迭代的字典键中获取值:

    for ingredient in MENU:
       print(MENU[ingredient]["ingredients"].values())
    

    或者如果你只是想 product_2 :

    print(MENU["product_2"]["ingredients"].values())
    

    如果您想要钥匙:

    print(list(MENU["product_2"]["ingredients"]))
    

    print(MENU["product_2"]["ingredients"].keys())