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

前端 未结 16 659
轮回少年
轮回少年 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条回答
  •  萌比男神i
    2020-12-04 10:03

    This function works for non-hashable values. I also think that it is clear and easy to read.

    def isSubDict(subDict,dictionary):
        for key in subDict.keys():
            if (not key in dictionary) or (not subDict[key] == dictionary[key]):
                return False
        return True
    
    In [126]: isSubDict({1:2},{3:4})
    Out[126]: False
    
    In [127]: isSubDict({1:2},{1:2,3:4})
    Out[127]: True
    
    In [128]: isSubDict({1:{2:3}},{1:{2:3},3:4})
    Out[128]: True
    
    In [129]: isSubDict({1:{2:3}},{1:{2:4},3:4})
    Out[129]: False
    

提交回复
热议问题