You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python多层嵌套字典遍历:提取指定信息用于前端展示

解决Python多层嵌套字典遍历提取指定信息的问题

修正后的遍历代码(控制台输出)

首先避免使用dict作为变量名(会覆盖Python内置类型),然后通过直接访问内层字典的price键提取指定值,同时控制输出格式:

food_dict = {
  "fruits": {
    "banana": {
       "code": "fgr",
       "price": "4€"
    },
    "apple": {
        "code": "fgf",
        "price": "1€"
    }
  },
  "vegetables": {
    "spinach": {
       "code": "hgg",
       "price": "2€"
    },
    "carrot": {
        "code": "hgl",
        "price": "3€"
    }
  }
}

# 遍历外层类别
for category, items in food_dict.items():
    print(f"{category.capitalize()}:")
    # 遍历类别下的物品
    for item_name, item_details in items.items():
        print(f"  {item_name.capitalize()}:")
        # 提取并打印指定的price值
        print(f"    {item_details['price']}")

运行后控制台输出与期望格式一致:

Fruits:
  Banana:
    4€
  Apple:
    1€
Vegetables:
  Spinach:
    2€
  Carrot:
    3€

适配前端的数据格式处理

如果要把数据传给前端,建议转换成JSON格式,方便前端解析渲染:

import json

# 整理成结构化数据
frontend_data = []
for category, items in food_dict.items():
    category_info = {
        "category": category.capitalize(),
        "items": [
            {"name": item_name.capitalize(), "price": item_details["price"]}
            for item_name, item_details in items.items()
        ]
    }
    frontend_data.append(category_info)

# 输出JSON字符串
print(json.dumps(frontend_data, indent=2))

输出的JSON结构如下,前端可直接遍历数组渲染类别和物品:

[
  {
    "category": "Fruits",
    "items": [
      {
        "name": "Banana",
        "price": "4€"
      },
      {
        "name": "Apple",
        "price": "1€"
      }
    ]
  },
  {
    "category": "Vegetables",
    "items": [
      {
        "name": "Spinach",
        "price": "2€"
      },
      {
        "name": "Carrot",
        "price": "3€"
      }
    ]
  }
]

内容的提问来源于stack exchange,提问作者Xershy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 23:57:26