Python:如何向嵌套列表内新增字典且不覆盖原有配置内容?
问题1:配置被覆盖的解决方法
你现有代码的核心问题是直接将filters["children"]赋值为空字典,原有存储在列表结构里的所有旧过滤器配置自然被完全覆盖。从给出的配置结构可以看出,children字段的类型是列表,每个子项是单个条件或分组字典。
如果仅需要新增条件,参考如下修改:
filters = self._get_filters(pipeline) source_fields = self.ssi_get_filter_source_fields(pipeline) for source_field in source_fields.json_path("$.data"): if source_field["descriptor"] == filter_source_field: # 构造新的条件字典 new_condition = { "type": "CONDITION", "id": 123, # 建议生成唯一ID避免冲突 "field": source_field, "operatorId": cond, "targetText": test } # 追加到children列表末尾,不覆盖原有内容 filters["children"].append(new_condition)
如果需要实现「存在则修改、不存在则新增」的能力,可增加匹配判断逻辑:
filters = self._get_filters(pipeline) source_fields = self.ssi_get_filter_source_fields(pipeline) for source_field in source_fields.json_path("$.data"): if source_field["descriptor"] == filter_source_field: new_condition = { "type": "CONDITION", "id": 123, "field": source_field, "operatorId": cond, "targetText": test } # 先遍历查找是否有匹配的已有条件,匹配规则可自行调整 exist_flag = False for idx, item in enumerate(filters["children"]): if item.get("type") == "CONDITION" and item["field"]["descriptor"] == filter_source_field: filters["children"][idx] = new_condition exist_flag = True break # 没有匹配到对应条件则执行新增 if not exist_flag: filters["children"].append(new_condition)
问题2:返回结果出现单引号的原因
你看到的单引号是Python字典对象的原生字符串表示形式,Python默认使用单引号包裹字符串,不属于代码错误。如果你需要输出标准JSON格式(双引号),可以使用json模块将字典转为JSON字符串:
import json # 转换为标准JSON字符串,ensure_ascii=False保留中文,indent=4格式化缩进 json_str = json.dumps(your_dict, ensure_ascii=False, indent=4)
如果是通过接口返回数据,只要服务框架会自动将Python字典序列化为JSON,实际传输的内容仍为标准双引号格式,不需要额外处理。
内容的提问来源于stack exchange,提问作者oksa23
相关产品推荐
相关产品推荐

