如何从字典列表中移除子集字典
移除字典列表中的子集字典
给定如下字典列表:
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)
代码说明
is_subset函数:通过验证d1的每一组键值对都存在于d2中,判断d1是否为d2的子集。- 遍历原列表时,用
any()函数检查当前字典是否被其他字典包含。若不存在这样的包含关系,就将该字典加入结果列表。
内容的提问来源于stack exchange,提问作者milevskyid
相关产品推荐
相关产品推荐

