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

Python如何基于用户输入过滤JSON配置字典获取指定片段

问题修正方案

你的现有代码存在两处缺失逻辑,导致输出多余空字段和无效条目:

  1. 没有丢弃过滤后为空的颜色分类字典
  2. 没有丢弃Fruits字段完全无匹配结果的区域条目

修正后代码

import json

superset_config = """
[ {
      "Area":"Texas",
      "Fruits": { 
                  "RED": {
                           "Apple":["val1"],
                           "Grapes":["green"]
                         },
                  "YELLOW": {"key2":["val2"]} 
                }
  },
  {
      "Area":"Dallas",
      "Fruits": { 
                    "GREEN": { "key3": ["val3"]} 
                } 
  }
]
"""
inputs = ['Apple'] # input list

derived_config = []
for each_src in json.loads(superset_config):
    temp = {}
    temp_inner = {}
    # 处理Fruits字段
    for color, fruit_map in each_src['Fruits'].items():
        # 过滤匹配的水果
        matched_fruits = {k:v for k,v in fruit_map.items() if k in inputs}
        # 仅当该颜色下有匹配水果时才保留该颜色分类
        if matched_fruits:
            temp_inner[color] = matched_fruits
    # 仅当Fruits有匹配结果时才保留当前区域条目
    if temp_inner:
        temp['Area'] = each_src['Area']
        temp['Fruits'] = temp_inner
        derived_config.append(temp)

运行结果

[
    {
        "Area": "Texas",
        "Fruits": {
            "RED": {
                "Apple": ["val1"]
            }
        }
    }
]

如果需要把水果对应的列表值取出为单个元素,可把matched_fruits = {k:v for k,v in fruit_map.items() if k in inputs}改为matched_fruits = {k:v[0] for k,v in fruit_map.items() if k in inputs}即可完全匹配你给出的期望输出格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 09:39:02