使用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函数实现两个逻辑:
- 移除每个字典中
notes列表里所有val=0的元素 - 如果处理后某个字典的
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
相关产品推荐
相关产品推荐

