Python如何基于用户输入过滤JSON配置字典获取指定片段
问题修正方案
你的现有代码存在两处缺失逻辑,导致输出多余空字段和无效条目:
- 没有丢弃过滤后为空的颜色分类字典
- 没有丢弃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
相关产品推荐
相关产品推荐

