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

使用Python遍历字典列表,删除notes中val=0的元素及空notes字典

问题描述

给定如下Python字典列表:

dict_list=[
    {
      "notes": [
          {"Id": "Id1","val": -1},
          {"Id": "Id2","val": 0},
          { "Id": "Id3","val": 1}
              ],
      "user_id": "u_id1"
    },
    {
      "notes": [
          {"Id": "Id4","val": -1},
          {"Id": "Id5","val": 1}
              ],
      "user_id": "u_id2"
    },
    {
      "notes": [
          {"Id": "Id4","val": 0}
              ],
      "user_id": "u_id3"
    }
  ]

需要编写Python函数实现两个逻辑:

  1. 移除每个字典中notes列表里所有val=0的元素
  2. 如果处理后某个字典的notes列表为空,则将该字典从原列表中移除

预期输出如下:

dict_list_new=[
    {
      "notes": [
          {"Id": "Id1","val": -1},
          { "Id": "Id3","val": 1}
              ],
      "user_id": "u_id1"
    },
    {
      "notes": [
          {"Id": "Id4","val": -1},
          {"Id": "Id5","val": 1}
              ],
      "user_id": "u_id2"
    }
  ]
解决方案

可以通过遍历+过滤的方式实现需求,代码如下:

def process_dict_list(input_list):
    processed_list = []
    for item in input_list:
        # 过滤掉notes中val为0的元素
        filtered_notes = [note for note in item["notes"] if note["val"] != 0]
        # 仅保留notes非空的字典
        if filtered_notes:
            # 复制原字典并更新notes,避免修改原数据
            new_item = item.copy()
            new_item["notes"] = filtered_notes
            processed_list.append(new_item)
    return processed_list

# 调用函数得到结果
dict_list_new = process_dict_list(dict_list)

逻辑说明:

  • 遍历输入列表中的每个字典,对notes字段用列表推导式过滤掉val=0的元素
  • 检查过滤后的notes是否为空,非空则复制原字典并更新notes字段,加入结果列表
  • 使用copy()是为了避免修改原始输入数据,保持数据独立性

运行上述代码后,输出结果与预期完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 19:50:29