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

前端 未结 16 689
轮回少年
轮回少年 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:15

    I know this question is old, but here is my solution for checking if one nested dictionary is a part of another nested dictionary. The solution is recursive.

    def compare_dicts(a, b):
        for key, value in a.items():
            if key in b:
                if isinstance(a[key], dict):
                    if not compare_dicts(a[key], b[key]):
                        return False
                elif value != b[key]:
                    return False
            else:
                return False
        return True
    

提交回复
热议问题