Python: Check if one dictionary is a subset of another larger dictionary

前端 未结 16 681
轮回少年
轮回少年 2020-12-04 09:29

I\'m trying to write a custom filter method that takes an arbitrary number of kwargs and returns a list containing the elements of a database-like list that contain

16条回答
  •  无人及你
    2020-12-04 10:03

    Here is a solution that also properly recurses into lists and sets contained within the dictionary. You can also use this for lists containing dicts etc...

    def is_subset(subset, superset):
        if isinstance(subset, dict):
            return all(key in superset and is_subset(val, superset[key]) for key, val in subset.items())
    
        if isinstance(subset, list) or isinstance(subset, set):
            return all(any(is_subset(subitem, superitem) for superitem in superset) for subitem in subset)
    
        # assume that subset is a plain value if none of the above match
        return subset == superset
    

提交回复
热议问题