Python中处理字典列表,删除df键提取其余键值对生成新列表的方法
Python字典列表批量删除指定键的实现方法
实现代码
写法1:推导式(推荐,简洁且不修改原数据)
l1 = [{"year":"<year>", "df":"<df1>"}, {"system":"<system>","df":"<df2>"}, {"year":"<year>","month":"<month>","system":"<system>","df":"<df3>"}] # 核心逻辑:遍历每个字典,过滤掉键为df的项 l2 = [{k: v for k, v in item.items() if k != "df"} for item in l1] print(l2)
输出结果和预期完全一致:
[{'year': '<year>'}, {'system': '<system>'}, {'year': '<year>', 'month': '<month>', 'system': '<system>'}]
写法2:循环+pop(适合需要扩展处理逻辑的场景)
如果后续还要对每个字典做其他定制处理,可以用显式循环的写法,pop方法的第二个参数设置为None可以避免字典不存在df键时报错:
l2 = [] for item in l1: # 先拷贝原字典,避免修改原列表里的原始数据 new_item = item.copy() new_item.pop("df", None) l2.append(new_item)
内容的提问来源于stack exchange,提问作者EM_77
相关产品推荐
相关产品推荐

