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

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

    My function for the same purpose, doing this recursively:

    def dictMatch(patn, real):
        """does real dict match pattern?"""
        try:
            for pkey, pvalue in patn.iteritems():
                if type(pvalue) is dict:
                    result = dictMatch(pvalue, real[pkey])
                    assert result
                else:
                    assert real[pkey] == pvalue
                    result = True
        except (AssertionError, KeyError):
            result = False
        return result
    

    In your example, dictMatch(d1, d2) should return True even if d2 has other stuff in it, plus it applies also to lower levels:

    d1 = {'a':'2', 'b':{3: 'iii'}}
    d2 = {'a':'2', 'b':{3: 'iii', 4: 'iv'},'c':'4'}
    
    dictMatch(d1, d2)   # True
    

    Notes: There could be even better solution which avoids the if type(pvalue) is dict clause and applies to even wider range of cases (like lists of hashes etc). Also recursion is not limited here so use at your own risk. ;)

提交回复
热议问题