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

如何从字典列表中移除子集字典

移除字典列表中的子集字典

给定如下字典列表:

l = [
    {'zero': 'zero', 'one': 'example', 'two': 'second'}, 
    {'zero': 'zero', 'one': 'example', 'two': 'second', 'three': 'blabla'},
    {'zero': 'zero'},
    {'zero': 'non-zero', 'one': 'example'}
]

需要生成一个新列表,仅保留那些未被其他字典完全包含的字典,预期结果如下:

res = [
    {'zero': 'zero', 'one': 'example', 'two': 'second', 'three': 'blabla'},
    {'zero': 'non-zero', 'one': 'example'}
]

解决方案

通过遍历每个字典,检查它是否是列表中其他字典的子集即可实现需求。核心逻辑:对于字典d,如果不存在另一个字典other_d(other_d != d)能完全包含d的所有键值对,就保留d。

实现代码如下:

def is_subset(d1, d2):
    # 判断d1是否是d2的子集
    return all(item in d2.items() for item in d1.items())

l = [
    {'zero': 'zero', 'one': 'example', 'two': 'second'}, 
    {'zero': 'zero', 'one': 'example', 'two': 'second', 'three': 'blabla'},
    {'zero': 'zero'},
    {'zero': 'non-zero', 'one': 'example'}
]

res = []
for d in l:
    # 检查当前字典是否未被任何其他字典包含
    if not any(is_subset(d, other) and d != other for other in l):
        res.append(d)

print(res)

代码说明

  1. is_subset函数:通过验证d1的每一组键值对都存在于d2中,判断d1是否为d2的子集。
  2. 遍历原列表时,用any()函数检查当前字典是否被其他字典包含。若不存在这样的包含关系,就将该字典加入结果列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 07:50:10