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

前端 未结 16 664
轮回少年
轮回少年 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 09:54

    Use this wrapper object that provides partial comparison and nice diffs:

    
    class DictMatch(dict):
        """ Partial match of a dictionary to another one """
        def __eq__(self, other: dict):
            assert isinstance(other, dict)
            return all(other[name] == value for name, value in self.items())
    
    actual_name = {'praenomen': 'Gaius', 'nomen': 'Julius', 'cognomen': 'Caesar'}
    expected_name = DictMatch({'praenomen': 'Gaius'})  # partial match
    assert expected_name == actual_name  # True
    

提交回复
热议问题